预计会有五个实例接收一次

时间:2014-04-25 13:54:11

标签: ruby rspec

我的测试数据库中有五个ProxyServer个实例。

我希望我的方法在这五个实例中的每一个上调用一次blacklist!

我试过这四个:

expect_any_instance_of(ProxyServer).to receive(:blacklist!).exactly(5).times
# I know, that this is not supposed to work

expect_any_instances_of(ProxyServer).to receive(:blacklist!).exactly(5).times
# undefined method

ProxyServer.all.each do |proxy|
  expect(proxy).to receive(:blacklist!)
end

ProxyServer.count.times do
  expect_any_instance_of(ProxyServer).to receive(:blacklist!)
end

他们都错了。什么是对的?

1 个答案:

答案 0 :(得分:0)

你的倒数第二种方法应该可以正常工作。以下示例成功,例如:

class ProxyServer

  @@servers = []

  def initialize
    @@servers << self
  end

  def blacklist!
  end

  def self.all
    @@servers
  end

end

describe 'my test' do
  it 'should call blacklist! on each of the ProxyServer instances' do
    5.times { ProxyServer.new }
    ProxyServer.all.each { |server| expect(server).to receive(:blacklist!) }
    ProxyServer.all.each { |server| server.blacklist!}
  end
end