1

如何使用 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)
4

2 回答 2

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)
于 2012-11-19T05:24:01.970 回答
2

来自文档的示例: http ://rubydoc.info/gems/rspec-mocks/frames

double.should_receive(:<<).with("illegal value").once.and_raise(ArgumentError)
于 2012-11-19T05:25:29.373 回答