RSpec: how to check if a method is called?

When writing RSpec tests, I find that I write a lot of code that looks like this to guarantee that the method was called during the test (for the sake of argument, let me say that I can not poll the state of the object after the call, because the operation that it performs method, not just see the effect).

describe "#foo" it "should call 'bar' with appropriate arguments" do called_bar = false subject.stub(:bar).with("an argument I want") { called_bar = true } subject.foo expect(called_bar).to be_true end end 

I want to know: is there more syntax than this? Have I really missed some funky RSpec awesomeness that would reduce the code above to a few lines? should_receive sounds like he should do it, but reading further, it sounds like it's not quite what he is doing.

+79
ruby ruby-on-rails rspec
Jan 21 '14 at 15:27
source share
3 answers
 it "should call 'bar' with appropriate arguments" do expect(subject).to receive(:bar).with("an argument I want") subject.foo end 
+89
Jan 21 '14 at 16:01
source share

In the new rspec expect syntax, this will be:

 expect(subject).to receive(:bar).with("an argument I want") 
+90
Mar 24 '14 at 7:45
source share

Below should work

 describe "#foo" it "should call 'bar' with appropriate arguments" do subject.stub(:bar) subject.foo expect(subject).to have_received(:bar).with("Invalid number of arguments") end end 

Documentation: https://github.com/rspec/rspec-mocks#expecting-arguments

+26
Jan 21 '14 at 15:48
source share



All Articles