在我的Rails控制器测试中,为什么我得到NoM​​ethodError:未定义的方法'格式'对于字符串?

时间:2016-09-08 17:02:50

标签: ruby-on-rails

我试图为现有的应用程序添加测试,这些测试有点不同寻常。我可以让它在开发服务器上呈现一个页面。但是当我添加一个控制器测试时,每当我渲染一个视图时,我都会收到以下错误:

NoMethodError: undefined method `formats' for "foo":String
test/controllers/dashboard_controller_test.rb:15:in `block in <class:DashboardControllerTest>'

以下是代码:

# config/routes.rb
get 'foo', to: 'dashboard#foo'

# app/controllers/dashboard_controller.rb
class DashboardController < ApplicationController
  def foo
    #render plain: 'ok'
  end
end

# app/views/dashboard/foo.html.erb
ok!

# app/views/layouts/application.rb
<!DOCTYPE html>
<html>
<head>
  <title>Dashboard</title>
</head>
<body>

<%= yield %>

</body>
</html>

# test/controllers/dashboard_controller_test.rb
require 'test_helper'

class DashboardControllerTest < ActionController::TestCase
  test "get foo" do
    get :foo
    assert_response :success
  end
end

我在浏览器中访问/foo并获得ok!

我运行我的测试,我得到上面的错误。

如果我取消注释render plain中的DashboardController#foo行,则测试通过。

当测试尝试渲染视图时,看起来会出现问题,但我无法弄清楚错误信息并没有给我提供太多帮助。这个错误意味着什么?

更新

注意到应用程序正在使用render_anywhere gem。我想知道这是否与它有关。

1 个答案:

答案 0 :(得分:0)

禁用render_anywhere gem确实解决了这个问题。它被包含在佣金任务中。

rake任务没有经过测试,所以我现在就这样简单地解决了这个问题:

unless Rails.env.test?
  require 'render_anywhere'
  include RenderAnywhere
end