你好,
我正在尝试干燥我的一些规范。我提取了一个断言类,它执行一些 should
操作...但是大多数 RSpec 期望魔法不再起作用。
我将尝试构建一个简单的示例来展示我的问题。
被测对象:
class Foo
def has_bar?; true; end
end
我的断言类:
class MyAssertions
def self.assert_everything_is_ok
@foo = Foo.new
@foo.has_bar?.should == true # works!
@foo.has_bar?.should be_true # undefined local variable or method `be_true`
@foo.should have_bar # undefined local variable or method `have_bar`
end
end
我的规范:
it "tests something" do
@foo = Foo.new
@foo.should have_bar # works!
MyAssertion.assert_everything_is_ok # does not work, because of errors above
end
为什么我不能在普通的旧 ruby 对象中使用 rspec 期望的语法糖?
最佳答案
经过多次尝试,我想出了这个解决方案:
class MyAssertions
include RSpec::Matchers
def assert_everything_is_ok
@foo = Foo.new
@foo.has_bar?.should == true # works!
@foo.has_bar?.should be_true # works now :)
@foo.should have_bar # works now :)
end
end
诀窍是 include
RSpec::Matchers
模块。我使用实例方法而不是类方法。
关于ruby - 如何在 PORO 中使用 RSpec 期望,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22959785/