【问题标题】:Rails rspec render_template errorRails rspec render_template 错误
【发布时间】:2015-04-21 14:31:44
【问题描述】:

我正在关注 Hartl 的 Ruby on Rails 教程,但无法弄清楚为什么下面的代码不断给我这个错误:

Failure/Error: expect(response).to render_template("membres/show")
     NoMethodError:
       undefined method `body' for nil:NilClass

代码:

require 'rails_helper'

RSpec.describe "Membres", :type => :request do  

  include Capybara::DSL

  describe "une inscription" do
    describe "ratée" do
      it "ne devrait pas créer un nouvel utilisateur" do
        visit signup_path
        fill_in "Nom",          :with => ""
        fill_in "Email",        :with => ""
        fill_in "Password",     :with => ""
        fill_in "Confirmation", :with => ""
        click_button "Inscription"
        expect(response).to render_template("membres/show")
        expect(response).to have_tag("div#error_explanation")
      end
    end
  end
end

我尝试在错误的行上使用“页面”而不是“响应”,我也尝试使用其他链接而不是“成员/显示”,但什么也没做。

现在有人有什么想法吗?

编辑

我应该使用它绝对是“页面”而不是“响应”,但这仍然不能清除错误消息。

【问题讨论】:

  • 难道我不能在请求规范中使用 render_template 吗?
  • 我认为render_template 更适合控制器规格
  • 这会是 Rails 4 的新功能吗?因为我遵循的教程说将该测试放在请求规范中,并且该教程是关于 Rails 3 的。
  • 对不起,我把它和特性规范混在一起了,无论如何,我仍然认为如果不运行 getpost 请求,你不会得到响应对象,第二个期望是有道理的,但在用 page 替换 response 就像你说的那样,第一个期望应该移到用户控制器规范中才能工作
  • 我发现了一些东西。它说here render_template 应该在我的版本 rspec 3.2 中的请求规范中工作。它还说render_template 使用rails 的函数assert_template。我去那里问问。

标签: rspec3 ruby-on-rails-4.2


【解决方案1】:

这是解决该问题的一种方法。

在您的错误消息中查找“test_case.rb”的路径和错误行:

NoMethodError:
       undefined method `body' for nil:NilClass
     # /var/lib/gems/1.9.1/gems/actionpack-4.2.0/lib/action_controller/test_case.rb:111:in `assert_template'
     # ./spec/requests/membres_spec.rb:21:in `block (5 levels) in <top (required)>'
     # ./spec/requests/membres_spec.rb:23:in `block (4 levels) in <top (required)>'

在我的情况下,文件位于“/var/lib/gems/1.9.1/gems/actionpack-4.2.0/lib/action_controller/”,错误行是 111。

使用您喜欢的文本编辑器,以 root 身份打开“test_case.rb”,转到指定的行,它应该如下所示:

response.body

改成:

response.body if !response.nil?

而且你应该能够使用 render_template 或 assert_template 而不使用:

get

post

就我而言,我可以使用

visit

这不会创建“响应”对象,因此会出现错误消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2014-01-01
    • 1970-01-01
    相关资源
    最近更新 更多