0

我正在设置一个测试,应该期望调用两个“订阅者”实例:

  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),它会失败并显示该错误消息。如果我删除该行,测试运行顺利(没有错误的参数数量问题)。我究竟做错了什么?

4

1 回答 1

0

您得到的错误是因为 'times' 方法预计会被链接到其他“接收计数”期望之一。您可以使用以下任何一种:

should_receive(:send_message).with(@message).exactly(2).times
should_receive(:send_message).with(@message).at_most(2).times

您还可以使用不需要 'times' 方法的其他替代方法之一:

should_receive(:send_message).with(@message).twice
should_receive(:send_message).with(@message).at_most(:twice)

更多信息可以在rspec-mocks 文档中找到

您可能需要在创建订阅者之前设置期望:

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
于 2012-09-04T23:33:11.897 回答