lundi 16 mars 2020

Associated record is nil in integration test after saving in controller

In a controller I have an update method which creates a record (call it book), associates it to an existing record (call it author) and saves it.

Book belongs to one Author

add_author_to_book_controller.rb

def update
  @author = App::Models::Author.new(params)
  @book = App::Models::Book.where(id: params[:book_id]).first
  @book.author = @author
  @book.save!
  # this works fine...
  # puts @book.author.inspect 
  render json: { status: :ok }
end

add_author_to_book_controller_spec.rb

describe App::AddAuthorToBookController do
  describe '#update' do
    # this is a contrived example, there is more setup regarding creating the "book" properly...
    let(:name) { 'foobar' }
    let(:action) { xhr :put, :update, params }
    let(:params) { { first_name: name } }
    subject { book }
    before { action }

    it { expect(response.status).to eq 200 }
    it 'should save the author to the book' do
      # why is author nil here?
      # puts book.author.inspect
      expect(book.author.first_name).to eq name
    end
  end
end

I tried book.reload in the test but that didn't work. I'm new to rails, is there some conventional way of testing an associated record in a controller test?

Aucun commentaire:

Enregistrer un commentaire