ruby - 如何在 PORO 中使用 RSpec 期望

标签 ruby rspec rspec-expectations

你好,

我正在尝试干燥我的一些规范。我提取了一个断言类,它执行一些 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/

相关文章:

ruby - 哪个名字用得最多?

ruby-on-rails - 使用 Ruby 一次处理数组的 X 个元素的选项

ruby-on-rails - Rails Controller 测试 : Testing in isolation or integration?

ruby-on-rails - Rails 应用程序中的猴子修补数据库适配器

ruby - Savon 请求失败

ruby-on-rails - 规范不同的数据库

ruby - 匹配中多个期望语句的自定义断言消息

ruby - 我可以给嵌套 RSpec 匹配器起别名吗?

ruby - 如何执行一次并期望使用 RSpec 进行多次更改?

ruby-on-rails - cucumber 未定义方法