lundi 12 août 2019

Testing controllers with nested resources

I'm new to Ruby and I'm slowly making progress. I've just gotten to testing.

Please note that I'm not yet using any testing framework, merely what rails (5.2.3) provides out of the box.

I have authors who have many books has_many :books and books that belong to authors belongs_to :author.

These are my fixtures:

books.yml

tmaas:
  name: The Mysterious Affair at Styles
  published: 1920
  author_id: agatha_c

tgow:
  name: The Grapes of Wrath
  published: 1939
  author_id: john_s

authors.yml

agatha_c:
  name: Agatha Christie

john_s:
  name: John Steinbeck

I ran

rails test test/controllers/books_controller_test.rb

but I'm getting errors for these tests:

BooksControllerTest#test_should_update_book
BooksControllerTest#test_should_show_book
BooksControllerTest#test_should_get_edit
BooksControllerTest#test_should_destroy_book

The error is always the same, it can't find the book.

Error:
BooksControllerTest#test_should_destroy_book:
ActiveRecord::RecordNotFound: Couldn't find Book with 'id'=445166326 [WHERE "books"."author_id" = ?]
    app/controllers/books_controller.rb:72:in `set_book'
    test/controllers/books_controller_test.rb:47:in `block (2 levels) in <class:BooksControllerTest>'
    test/controllers/books_controller_test.rb:46:in `block in <class:BooksControllerTest>'


The problem comes from calling:

student_award_url id: books(:tmaas).id, author_id: @author.id

or

edit_student_award_url id: books(:tmaas).id, author_id: @author.id

@author is set in setup

setup do
    @author = authors(:agatha_c)
  end

The set_book function in the controller:

def set_book
      @book = @author.books.find(params[:id])
    end

What am I missing?

Aucun commentaire:

Enregistrer un commentaire