Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top