I am setting up a test that should expect calls on two “subscriber” instances:
it "sends out sms to all the subscribers" do
@user.subscribers.create!
@user.subscribers.create!
Subscriber.any_instance.should_receive(:send_message).with(@message).times(2)
post :create, {:broadcast => valid_attributes}
end
The actual code is:
def create
@broadcast = Broadcast.new(params[:broadcast])
current_user.subscribers.each do |subscriber|
subscriber.send_message(@broadcast.message)
end
...
The error:
Failure/Error: post :create, {:broadcast => valid_attributes}
ArgumentError:
wrong number of arguments (1 for 0)
# ./app/controllers/broadcasts_controller.rb:41:in `block in create'
# ./app/controllers/broadcasts_controller.rb:40:in `create'
# ./spec/controllers/broadcasts_controller_spec.rb:73:in `block (4 levels) in <top (required)>'
For some reason, if I add the line: Subscriber.any_instance.should_receive(:send_message).with(@message).times(2), it fails with that error message. If I remove that line, the test runs smoothly (no wrong number of argument problem). What am I doing wrong?
The error you’re getting is because the ‘times’ method is expected to be chained onto one of the other “receive count” expectations. You can use any one of the following:
You can also use one of the other alternatives that does not require the ‘times’ method:
More on that can be found in the rspec-mocks documentation
You may need to set the expectation BEFORE creating the subscribers: