Rails 4 Integration Testing Arrays not present in json object inside controllers

87 views Asked by At

I'm trying to create an integration testing for the creating of a record called books. I'm having problems creating the hash in the tests. This is my code:

test/integration/creating_book_test.rb

require 'test_helper'

class CreatingBookTest < ActionDispatch::IntegrationTest

  def setup
    @michael_lewis = Author.create!(name: 'Michael Lewis')
    @business = Genre.create!(name: 'Business')
    @sports = Genre.create!(name: 'Sports')
    @analytics = Genre.create!(name: 'Analytics')

  end

  test "book is created successfully" do
    post '/api/books', { book: book_attributes }.to_json, {
      'Accept' => 'application/json',
      'Content-Type' => 'application/json'
    }
    ... assertions...
  end

  def book_attributes
    {title: 'Moneyball',
     year: 2003,
     review: 'Lorem Ipsum',
     rating: 5,
     amazon_id: '10832u13kjag',
     author_ids: [@michael_lewis.id],
     genre_ids: [@business.id, @sports.id, @analytics.id]
    }
  end

end

In the controller, I'm whitelisting the params with:

  def book_params
    params.require(:book).permit(:title, :year, :review, :rating, :amazon_id, :author_ids, :genre_ids)
  end

The problem is that I'm not receiving :author_ids and :genre_ids in the controller. It seems like arrays don't get sent to the controller, so I can't test that associations work like they should.

Thanks.

1

There are 1 answers

0
Arup Rakshit On BEST ANSWER

You strong paramter declaration is wrong. Here is the fix:

params.require(:book).permit(:title, :year, :review, :rating, :amazon_id, author_ids: [], genre_ids: [])

From Permitted Scalar Values documentation :

..To declare that the value in params must be an array of permitted scalar values map the key to an empty array.