ActionController::UrlGenerationError: missing required keys: [:id]

房东的猫 提交于 2019-12-24 10:35:36

问题


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.



来源:https://stackoverflow.com/questions/24622123/actioncontrollerurlgenerationerror-missing-required-keys-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!