我不能为我的生活弄清楚这里出了什么问题。我有一个客户端模型和一个发票模型。
Client.rb
has_many :invoices, dependent: :destroy
Invoices.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”。
我做错了什么?
答案 0 :(得分: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)