0

我一生都无法弄清楚这里出了什么问题。我有一个客户模型和一个发票模型。

客户端.rb

has_many :invoices, dependent: :destroy

发票.rb

belongs_to :client

我有以下客户端规格:

it "destroys its children upon destruction" do
  i = FactoryGirl.create(:invoice) # As per the factory, the :client is the parent of :invoice and is automatically created with the :invoice factory

  lambda {
    i.client.destroy
  }.should change(Invoice.all, :count).by(-1)
end

这是我的工厂:

客户工厂

FactoryGirl.define do
  factory :client do
    city "MyString"
  end
end

发票厂

FactoryGirl.define do
  factory :invoice do
    association :client
    gross_amount 3.14
  end
end

如果我这样做i = FactoryGirl.create(:invoice),然后i.client.destroy在控制台中手动操作,发票实际上已被销毁。但由于某种原因,测试失败,给我“计数应该被-1改变,但被改变了0”。

我究竟做错了什么?

4

1 回答 1

2

的返回值Invoice.all是一个数组,因此数据库操作不会影响它。当您销毁记录时,该数组不会更改,并且should change(receiver, message)只会发送message到相同的receiver. 尝试:

lambda {
  i.client.destroy
}.should change(Invoice, :count).by(-1)

或者

lambda {
  i.client.destroy
}.should change{Invoice.all.count}.by(-1)
于 2013-01-02T21:17:32.877 回答