I have a "Book" model and a "BookFormat" model (for "hardcover", "paperback" and so on). The book model belongs_to book_format, and book_format has_many books. The book model hence has a book_format_id for the association. However this rspec test fails - the result is a 422 (unprocessable entity) instead of a 3xx (redirect). Not sure what I am doing wrong.
require 'rails_helper'
RSpec.describe BooksController, type: :controller do
context 'Basic book routes' do
... (stuff omitted)
describe 'CREATE /new' do
it 'creates a book when the title and format is present' do
post :create, params: { book: { title: 'A new book', book_format_id: '0' } }
expect(response).to redirect_to(assigns(:book))
end
end
end
end
The exact error from running rspec is:
1) BooksController Basic book routes GET /show CREATE /new creates a book when the title and format is present
Failure/Error: expect(response).to redirect_to(assigns(:book))
Expected response to be a <3XX: redirect>, but was a <422: Unprocessable Entity>
Response body:
# ./spec/requests/books_spec.rb:30:in `block (5 levels) in <top (required)>'
Amended test - trying to ensure that the book_format ID really exists:
require 'rails_helper'
RSpec.describe BooksController, type: :controller do
before(:all) do
@hardcover = create(:hardcover)
end
context 'Basic book routes' do
describe 'CREATE /new' do
it 'creates a book when the title and format is present' do
post :create, params: { book: { title: 'A new book', book_format_id: @hardcover.id } }
debugger
expect(response).to redirect_to(assigns(:book))
end
And I have a factory:
FactoryBot.define do
factory :hardcover, class: BookFormat do
format { 'Hardcover' }
end
end