测试类的实例是否在调用将消息发送到所有实例的类方法时收到消息

时间:2013-05-08 17:37:39

标签: ruby-on-rails ruby rspec datamapper

虽然正确,标题需要一些解释:)

我有这堂课:

class Character
  include DataMapper::Resource

  def self.tick_all
    all.collect &:tick
  end

  def tick
    # do stuff
  end

end

正如您所看到的,在调用Character.tick_all时,其所有实例都应接收tick调用。它的工作原理是:当我启动一个控制台时,tick中的内容就完成了。但我不能让我的测试通过:

describe ".tick_all" do
  let(:instance) { FactoryGirl.create(:character) }
  it "invokes #tick for every instance" do
    Character.tick_all
    instance.should_receive(:tick)
  end
end

失败的例子:

Failure/Error: instance.should_receive(:tick)
  (#<Character:0x00000002fa4e28>).tick(any args)
      expected: 1 time
      received: 0 times

1 个答案:

答案 0 :(得分:1)

在方法调用之前,应该设置的期望:

describe ".tick_all" do
  let(:instance) { FactoryGirl.create(:character) }
  it "invokes #tick for every instance" do
    instance.should_receive(:tick)
    Character.tick_all
  end
end

UPD :上面的代码不起作用。这个变种怎么样?

describe ".tick_all" do
  it "invokes #tick for every instance" do
    Character.any_instance.should_receive(:tick)
    Character.tick_all
  end
end

UPD2 :Aaand又一个版本:

describe ".tick_all" do
  it "invokes #tick for every instance" do
    tick_count = 0
    Character.any_instance.stub(:tick) { tick_count += 1 }
    Character.tick_all

    tick_count.should == Character.count
    # or
    # expect{ Character.tick_all }.to change{tick_count}.by(Character.count)
  end
end