【问题标题】:Deleting children does work in real app, but not in test删除孩子在真实应用程序中确实有效,但在测试中无效
【发布时间】:2013-01-02 20:04:09
【问题描述】:

我终其一生都无法弄清楚这里出了什么问题。我有一个 Client 模型和一个 Invoice 模型。

客户端.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”。

我做错了什么?

【问题讨论】:

  • Rails 本身可以很好地测试关系,因此大多数人都不会打扰。但是您可以测试您的关系是否建立正确。查看stackoverflow.com/questions/2673041/…
  • 谢谢,我已经这样做了。但仅仅因为建立了关系并不意味着孩子会被摧毁。
  • 是的,奇怪的是它们没有在您的测试中被删除。只是一个想法,您是否测试过您的工厂实际上正在创建关联对象并保存它?否则我看不到任何明显的错误,所以它可能只是 RSpec 很奇怪......
  • 是的,控制台中的i = FactoryGirl.create(:invoice) 可以创建发票,并且它的客户端非常好......奇怪。

标签: ruby-on-rails rspec count tdd associations


【解决方案1】:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多