如何使用所需的belongs_to关联测试控制器创建操作?
如果我删除validates :address, presence: true
它可以正常工作,但这个验证是必要的。
模型/ accreditor.rb
class Accreditor < ActiveRecord::Base
belongs_to :address, dependent: :destroy
validates :address, presence: true
规格/控制器/ accreditors_controller_spec.rb
describe AccreditorsController do
describe 'POST #create' do
it 'saves the new accreditor in the database' do
address = FactoryGirl.create(:address)
accreditor = FactoryGirl.build(:accreditor, address: address)
expect{
post :create, accreditor: accreditor.attributes
}.to change(Accreditor, :count).by(1)
end
end
此外,认证机构和地址工厂也适用于所有其他控制器操作。
答案 0 :(得分:1)
如果你做了这个改变:
accreditor = FactoryGirl.build(:accreditor, address_id: address.id)
它应该有用。
但是你不应该在这里使用工厂,你应该直接在那里放置参数,因为这是发布表单的人的方式。
答案 1 :(得分:0)
这似乎是最好的解决方案。
describe 'POST #create' do
it 'saves the new accreditor in the database' do
expect{
post :create, accreditor: FactoryGirl.attributes_for(:accreditor,
address_attributes: FactoryGirl.attributes_for(:address))
}.to change(Accreditor, :count).by(1)
end