【问题标题】:How can I use rspec expectations and matchers outside of Rspec?如何在 Rspec 之外使用 rspec 期望和匹配器?
【发布时间】:2015-09-15 19:15:19
【问题描述】:

我有一个脚本已经演变成需要进行一些断言和匹配。

它是用 ruby​​ 编写的,我在 Gemfile 中包含了rspec 并需要它。

我发现这篇关于如何在irb 中使用的非常有用的 SO 帖子:

How to use RSpec expectations in irb

我还发现了以下内容:

Use RSpec's "expect" etc. outside a describe ... it block

class BF
   include ::Rspec::Matchers

   def self.test
     expect(1).to eq(1)
   end
end

BF.test

expect 行出现错误。

【问题讨论】:

  • ...你得到什么错误?

标签: ruby rspec rspec-expectations


【解决方案1】:

当您include 一个模块时,它会使其方法可用于类的实例。您的 test 方法是单例方法(“类方法”),而不是实例方法,因此永远无法访问混合模块提供的方法。要修复它,您可以这样做:

class BF
   include ::RSpec::Matchers

   def test
     expect(1).to eq(1)
   end
end

BF.new.test

如果您希望 RSpec::Matchers 方法可用于 BF 的单例方法,您可以改为 extend 模块:

class BF
   extend ::RSpec::Matchers

   def self.test
     expect(1).to eq(1)
   end
end

BF.test

【讨论】:

  • 啊,这就是我想要的扩展!马上试试!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多