【问题标题】:How to unit test accepts_nested_attributes_for with RSpec?如何使用 RSpec 对 Accepts_nested_attributes_for 进行单元测试?
【发布时间】:2013-03-02 13:35:30
【问题描述】:

在我的 Rails 应用程序中,我有一个 Invoice 和各种 Items

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

有人可以帮忙吗?

【问题讨论】:

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


    【解决方案1】:

    来自accept_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.
    

    文档没有具体说明 静默 的含义,但它可能不会引发异常......

    尝试在项目模型属性上设置一些验证,存在肯定会引发一些异常,结束应该足够响亮,以使 rspec expect{..}.to 阻止工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      • 2016-05-27
      • 2019-11-02
      相关资源
      最近更新 更多