如何用RSpec对accept_nested_attributes_for进行单元测试?

时间:2013-03-02 13:35:30

标签: ruby-on-rails ruby ruby-on-rails-3 rspec ruby-on-rails-3.2

在我的Rails应用程序中,我有InvoiceItems

class Invoice < ActiveRecord::Base

  attr_accessible :date, :recipient, :items_attributes

  accepts_nested_attributes_for :items, :reject_if => :all_blank, :allow_destroy => true

end

但是,我正在为该模型进行RSpec单元测试。例如,我想测试一个发票如果没有项目就会抛出错误。

这不起作用:

describe Invoice do

  it "is invalid without an item" do
    expect(build(:invoice, :items_attributes => {}).to have(1).errors_on(:items_attributes)
  end

end

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

来自accepts_nested_attributes_for documentation

You may also set a :reject_if proc to silently ignore any new record hashes if they fail to pass your criteria.

文档没有明确指出默默地的意思,但它可能没有抛出异常....

尝试在Item模型属性上设置一些验证,存在,这肯定会抛出一些异常,最终应该足够响亮,以便rspec expect {..}。阻止工作。