我正在设置一个测试,期望在两个“订户”实例上调用:
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
实际代码是:
def create
@broadcast = Broadcast.new(params[:broadcast])
current_user.subscribers.each do |subscriber|
subscriber.send_message(@broadcast.message)
end
...
错误:
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)>'
出于某种原因,如果我添加以下行:Subscriber.any_instance.should_receive(:send_message).with(@message).times(2)
,则会失败并显示该错误消息。如果我删除该行,测试运行顺利(没有错误的参数问题)。我做错了什么?
答案 0 :(得分:0)
您得到的错误是因为“时间”方法预计将被链接到其他“接收计数”期望之一。您可以使用以下任何一种方法:
should_receive(:send_message).with(@message).exactly(2).times
should_receive(:send_message).with(@message).at_most(2).times
您还可以使用其他一种不需要“时间”方法的替代方案:
should_receive(:send_message).with(@message).twice
should_receive(:send_message).with(@message).at_most(:twice)
有关详情,请参阅rspec-mocks documentation
您可能需要在创建订阅者之前设置期望:
it "sends out sms to all the subscribers" do
Subscriber.any_instance.should_receive(:send_message).with(@message).twice
@user.subscribers.create!
@user.subscribers.create!
post :create, {:broadcast => valid_attributes}
end