【问题标题】:RSpec Request Spec - missing required keys: [:id]RSpec 请求规范 - 缺少必需的键:[:id]
【发布时间】:2015-03-02 13:16:29
【问题描述】:

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

#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 post_path, {id: 1} 替换为get "posts/1",那么测试会按预期通过

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

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

    get post_path('1')
    

    【讨论】:

    • 谢谢史蒂夫!我尝试了第一个选项,但得到了 ArgumentError bad argument (expected URI object or URI string)。第二个选项虽然成功了。
    • 我想了解为什么在 params 哈希中传递 id 不起作用。如果您能对此提供任何见解,我将不胜感激。
    • 这是因为测试不是控制器测试,rspec 上下文通常会引用控制器...然后您可以使用符号调用 post 操作,您可以指定参数。控制器测试之外的获取只需要 URI 并且参数变为 posts/?id='1' 而不是 posts/1 RSpec.describe PostsController do;描述“获取帖子”;它“渲染帖子”做; post = Post.create;获取:show,id:post.id;期望(响应).to render_template(:show);结尾;结尾;看完这个...relishapp.com/rspec/rspec-rails/docs/controller-specs
    • 再次感谢!这真的很有帮助。我欠你选择的饮料。
    • 我很想喝杯茶。有多难过?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多