【问题标题】:How to test a mixed-in class method is being called with RSpec and Mocha?如何测试使用 RSpec 和 Mocha 调用的混合类方法?
【发布时间】:2013-05-15 21:44:22
【问题描述】:

我有一个模块:

module MyModule
  def do_something
    # ...
  end
end

由一个类使用如下:

class MyCommand
  extend MyModule

  def self.execute
    # ...
    do_something
  end
end

如何验证MyCommand.execute 调用do_something?我曾尝试使用 mocha 进行部分模拟,但在不调用 do_something 时它不会失败:

it "calls do_something" do
  MyCommand.stubs(:do_something)
  MyCommand.execute
end

【问题讨论】:

    标签: ruby rspec mocking ruby-mocha


    【解决方案1】:

    嗯,这是一个解决方案。

    正如我在this SO post 中提到的,模拟/存根有两种策略:

    1) 使用 mocha 的 expects 将在测试结束时自动断言。在您的情况下,这意味着如果在expects 之后没有调用MyCommand.execute,则测试将失败。

    2) 更具体/更有说服力的方法是使用存根和间谍的组合。存根使用您指定的行为创建假对象,然后间谍检查以查看是否有人调用了该方法。要使用您的示例(注意这是 RSpec):

    require 'mocha'
    require 'bourne'
    
    it 'calls :do_something when .execute is run' do
      AnotherClass.stubs(:do_something)
    
      MyCommand.execute
    
      expect(AnotherClass).to have_received(:do_something)
    end
    
    # my_command.rb
    class MyCommand
      def self.execute
        AnotherClass.do_something
      end
    end
    

    所以expect 行使用bourne 的匹配器来检查:do_something 是否在`MyCommand 上被调用。

    【讨论】:

      【解决方案2】:

      好的,看起来expects 是解决方案:

      it "calls do_something" do
        MyCommand.expects(:do_something)
        MyCommand.execute
      end
      

      【讨论】:

      • 刚刚有同样的问题,可以确认这个答案可以让我准确地期望一个类方法被调用
      猜你喜欢
      • 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
      相关资源
      最近更新 更多