0

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
10
  • i think i know the reason but for to be sure can you share the book objects error messages. Commented Aug 2, 2022 at 14:47
  • added above - but I only can post the error from rspec. I have a very similar test that tests whether a book is valid, and it works (model test, essentially book = Book.new(title: 'The Hobbit', book_format_id: 1), and then expect(book.valid?).to eq(true)) Commented Aug 2, 2022 at 15:15
  • i think your problem is presence validation of belongs_to relation. Here my answer for the same problem hope it helps stackoverflow.com/a/73197428/5194116 Commented Aug 2, 2022 at 15:27
  • thanks - yes I understand that. However I DO want this relation to be mandatory. As you can see - I am passing a book_format_id along with the params, so this should work out but it doesn't seem to... Commented Aug 2, 2022 at 15:49
  • then you should pass a book_format_id that belongs a persisted book_format record Commented Aug 2, 2022 at 16:07

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.