Testing Controller create action with belongs_to association

679 views Asked by At

How do you test a controller create action with a belongs_to association that is required? If I remove validates :address, presence: true it works, but this validation is necessary.

models/accreditor.rb

class Accreditor < ActiveRecord::Base
  belongs_to :address, dependent: :destroy
  validates :address, presence: true

spec/controllers/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

Also, the accreditor and address factories work for all other controller actions.

2

There are 2 answers

0
AudioBubble On BEST ANSWER

This appears to be the best solution.

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
1
MaurĂ­cio Linhares On

If you make this change:

accreditor = FactoryGirl.build(:accreditor, address_id: address.id)

It should work.

But you shouldn't be using a factory here, you should have placed the parameters directly there, since that's how someone posting a form would do.