ActionController :: UrlGenerationError:缺少必需的键:[:id] [英] ActionController::UrlGenerationError: missing required keys: [:id]
问题描述
我正在运行RSpec 3测试,并且对于这一特定路径也遇到了相同的错误:
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
我的资源:
resources :books, only: [:index, :show, :new, :create] do
resources :reviews, only: [:show, :new, :create] do
end
推荐答案
由于未定义要访问的书 ,因此引发了错误。丢失的键 id
是书的ID。因此,您应该将其更改为:
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)
请注意,您可以直接传递ID( book_path(book.id)
),但是如果不这样做,Rails会从传递的对象中推断出它。
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.
这篇关于ActionController :: UrlGenerationError:缺少必需的键:[:id]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!