如何使用Rspec模拟推送到类数组变量?这是一个过于简化的例子:
class Foo
attr_accessor :bar
def initialize
@bar = []
end
end
def some_method(foo)
foo.bar << "a"
end
假设我想为some_method编写一个规范,“它应该将新值推送到bar”。我该怎么做?
foo = Foo.new
foo.should_receive(WHAT GOES HERE???).with("a")
some_method(foo)
答案 0 :(得分:3)
为什么要嘲笑?当你试图与实际尝试测试的东西隔离时,你只需要模拟一些东西。在您的情况下,您似乎正在尝试验证调用some_method
会导致将项添加到您传入的对象的属性中。您可以直接测试它:
foo = Foo.new
some_method(foo)
foo.bar.should == ["a"]
foo2 = Foo.new
foo2.bar = ["z", "q"]
some_method(foo2)
foo2.bar.should == ["z", "q", "a"]
# TODO: Cover situation when foo.bar is nil since it is available as attr_accessor
# and can be set from outside of the instance
*在以下评论后编辑**
foo = Foo.new
bar = mock
foo.should_receive(:bar).and_return bar
bar.should_receive(:<<).with("a")
some_method(foo)
答案 1 :(得分:2)
来自docs的示例: http://rubydoc.info/gems/rspec-mocks/frames
double.should_receive(:<<).with("illegal value").once.and_raise(ArgumentError)