RSpec 请求规范 - 缺少必需的键:[:id]

RSpec Request Spec - missing required keys: [:id]

我在运行我的测试时遇到一个我不太明白的错误。

#The error
Failure/Error: get post_path, {id: 1}
 ActionController::UrlGenerationError:
   No route matches {:action=>"show", :controller=>"posts"} missing required keys: [:id]

规格如下。

#spec/requests/visitor_interaction_spec.rb

require 'rails_helper'

RSpec.describe 'Visitor', :type => :request do
  context 'following a post link' do
    it 'should redirect to the post' do
      get post_path, {id: 1}
      expect(response).to render_template(:show)
    end
  end
end

如果我用 get "posts/1" 替换 get post_path, {id: 1} 那么测试会按预期通过

在非控制器中 rspec 你用一个 uri 来做,但是你需要将参数传递给路径

get post_path('1')