ActionController :: UrlGenerationError:缺少必需的键:[:id]

时间:2014-07-08 00:49:49

标签: ruby-on-rails-4 rspec capybara factory-bot rspec-rails

我正在运行RSpec 3测试,并且在这个特定路径上遇到同样的错误:

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

我的测试还没有完成,所以我确定后面的一些代码可能不正确。但我无法让我的访问路径行运行:

...
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

在我的控制器中,我将show定义为:

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

1 个答案:

答案 0 :(得分:6)

由于您尚未定义您要访问的图书,因此引发了错误。缺失的密钥id是图书的ID。所以你应该把它改成:

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

visit book_path(book)

请注意,您可以直接传递ID(book_path(book.id)),但如果您没有Rails将从传递的对象推断出来。