【问题标题】:How can I use RSpec Expectations in PORO's如何在 PORO 中使用 RSpec 期望
【发布时间】:2014-04-09 10:28:18
【问题描述】:

你好,

我正在尝试干掉我的一些规格。我提取了一个 Assertion 类,它执行了几个 shoulds ...但大多数 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 期望的语法糖?

【问题讨论】:

    标签: ruby rspec rspec-expectations


    【解决方案1】:

    经过更多尝试,我想出了这个解决方案:

    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 模块。我曾使用 instance methods 而不是 class methods

    【讨论】:

      【解决方案2】:

      更“类似 RSpec”的方法是使用 custom matcher

      RSpec::Matchers.define :act_like_a_good_foo do
        match do
          # subject is implicit in example
          subject.has_bar?.should == true
          subject.should be_true  # predicate matchers defined within RSpec::Matchers
          subject.should have_bar
        end
      end
      
      describe Foo do
        it { should act_like_a_good_foo }
      end
      

      【讨论】:

      • 很好。感谢您指出了这一点。它非常适合我发布的简化示例。然而,我的实际问题更加复杂,并且具有需要访问匹配器的页面对象和行为对象(在规范本身之外)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      相关资源
      最近更新 更多