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

And*_*anc 3 rspec ruby-on-rails

我在运行测试时遇到一个我无法弄清楚的错误。

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

下面是规格。

#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
Run Code Online (Sandbox Code Playgroud)

如果我替换为get post_path, {id: 1},get "posts/1"则测试按预期通过

Ste*_*zyn 6

在非控制器 rspec 中,您使用 uri 执行此操作,但随后您需要将参数传递给路径

get post_path('1')
Run Code Online (Sandbox Code Playgroud)