我正在尝试在Campaign
模型上测试验证。我有一个允许用户Create a Campaign
的表单,该表单应该要求他们在保存之前选择program
。
我试着在这里跟几个答案,但是无法让它们起作用。这是我到目前为止所拥有的......
关系..
class Campaign < ActiveRecord::Base
belongs_to :program
validates_associated :program,
message: "You need to choose a Program."
end
class Program < ActiveRecord::Base
has_many :campaigns
end
..和规范。
it 'validates associated campaign' do
campaign = build(:campaign)
expect(campaign.save).to be false
expect(campaign.errors).to eq "You need to choose a Program."
end
失败..
Failures:
1) Campaign validates associated campaign
Failure/Error: expect(campaign.save).to be false
expected false
got true
# ./spec/models/campaign_spec.rb:34:in `block (2 levels) in <top (required)>'
答案 0 :(得分:1)
validates_associated
仅在存在关联对象时才有效。在您的示例规范中,广告系列工厂(我假设)不会添加关联的程序,因此不会执行验证,并且会保存广告系列。
您要找的是validates :program, presence: true
,如果程序丢失,valid?
将返回false。