【问题标题】:Rspec: mock a nested/dependency injected objectRspec:模拟嵌套/依赖注入对象
【发布时间】:2012-05-01 22:41:57
【问题描述】:

我无法模拟注入的对象。例如:

class Foo
  def initialize(bar = Bar.new)
    @bar = bar
  end

  def run
    @bar.do_something_cool
  end
end

# Rspec
describe Foo do
  it "should do something cool" do
    mock_bar = mock("bar")
    mock_bar.stub(:do_something_cool).and_return(nil)

    real_foo = Foo.new(mock_bar)
    real_foo.run

    mock_bar.should_receive(:do_something_cool).once
  end
end

如果我运行这个,规范会失败,因为它说“do_something_cool”永远不会被调用。

 expected: 1 time
 received: 0 times

但是,如果我不存根“do_something_cool”,我会收到以下错误

Mock "bar" received unexpected message :do_something_cool with (no args)

有什么想法吗?

【问题讨论】:

    标签: ruby dependency-injection rspec mocking


    【解决方案1】:
    mock_bar.should_receive(:do_something_cool).once 
    

    应该在之前

    real_foo.run
    

    【讨论】:

    • 我一直希望 RSpec 的 DSL 允许模拟对象以不那么从后到前的方式使用,例如:expect { some_code }.to invoke(mock, :do_something_cool).once
    • 这种模拟模式被称为“测试间谍”。它是一个可以记住发生在它身上的事情的对象,因此您可以在事后断言已经发生的事情。您最初通常将它用作存根,因此您可以设置它的状态/行为。看看在 C# 中的 Moq 或 ruby​​ 中的 notahat.com/not_a_mock 中“验证”是如何工作的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 2021-11-23
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多