1

How do you mock a push into a class array variable using Rspec? Here is an over-simplified example:

class Foo
  attr_accessor :bar
  def initialize
    @bar = []
  end
end

def some_method(foo)
  foo.bar << "a"
end

Say I want to write a spec for some_method that "it should push a new value to bar". How do I do that?

foo = Foo.new
foo.should_receive(WHAT GOES HERE???).with("a")
some_method(foo)

2 Answers 2

3

Why mock anything? You only need to mock something when it is a dependency that you are trying to isolate from what you are actually trying to test. In your case, you seem to be trying to verify that calling some_method results in adding an item to a property of an object you passed in. You can simply test it directly:

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

* EDITED After Comments Below **

foo = Foo.new
bar = mock
foo.should_receive(:bar).and_return bar
bar.should_receive(:<<).with("a")
some_method(foo)
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, sorry, I might have over-simplified my example too much. There is a dependency on an external class in my real code. Good answer though.
This also works well for stubbing (and set an expectation for) a has_and_belongs_to_many (HABTM) association. Thank you :)
2

Example from docs: http://rubydoc.info/gems/rspec-mocks/frames

double.should_receive(:<<).with("illegal value").once.and_raise(ArgumentError)

2 Comments

So in Lynn's example, it will be foo.should_receive(:<<).with("a")
@PrakashMurthy: In this case, though, foo isn't receiving the <<, bar is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.