ActionController::UrlGenerationError: missing requ

2019-07-24 17:53发布

问题:

I'm running RSpec 3 tests and am getting this same error for this one particular path:

 Failure/Error: visit book_path
 ActionController::UrlGenerationError:
 No route matches {:action=>"show", :controller=>"books"} missing required keys: [:id]

My test isn't quite finished, so I'm sure some of the latter code might be incorrect. But I can't get my visit path line to run:

...
book = FactoryGirl.build(:book)
reviews = FactoryGirl.build_list(:review, 5, book: book)

visit book_path

reviews.each do |review|
  expect(page).to have_content(review.rating)
  expect(page).to have_content(review.body)
  expect(page).to have_content(review.timestamp)
end

  expect(page).to have_content('House of Leaves')
  expect(page).to have_content('Mark Z. Danielewski')
  expect(page).to have_content('Horror')
end

In my controller, I have show defined as:

def show
  @book = Book.find(params[:id])
  @reviews = @book.reviews.order('created_at DESC')
  @review = Review.new
end

And my resources:

resources :books, only: [:index, :show, :new, :create] do
  resources :reviews, only: [:show, :new, :create] do
end

回答1:

It's raising an error because you haven't defined which book you'd like to visit. The missing key, id, is the ID of the book. So you should change this to:

book = FactoryGirl.build(:book)
reviews = FactoryGirl.build_list(:review, 5, book: book)

visit book_path(book)

Note that you can pass in the ID directly (book_path(book.id)), but if you don't Rails will infer it from the object passed.