为Rails创建一个虚拟控制器问题无法正常工作

时间:2014-10-08 03:38:50

标签: ruby-on-rails ruby ruby-on-rails-4 minitest

我试图根据this example动态创建一个控制器来测试我的rails控制器问题。

我的代码看起来像这样

require 'test_helper'

class RequireAuthenticationTest < ActionController::TestCase
  test "Throws token required error" do
    @controller = RequireAuthenticationTestController.new(:index) { require_authentication; render :nothing => true }
    get :index

    assert_response :success
  end
end

class RequireAuthenticationTestController < ActionController::Base
  include RequireAuthentication

  def initialize(method_name, &method_body)
    self.class.send(:define_method, method_name, method_body)
  end
end

每当我尝试运行代码时,我都会收到错误

  

RequireAuthenticationTest#test_Throws_token_required_error:   ActionController :: UrlGenerationError:没有路由匹配   {:action =&gt;&#34; index&#34;,:controller =&gt;&#34; require_authentication_test&#34;}       test / controllers / concerns / require_authentication_test.rb:7:在`block in&#39;

关于我做错了什么的任何建议?谢谢!

1 个答案:

答案 0 :(得分:0)

您可能需要为测试控制器定义路由。这是我用来测试我的面包屑的代码:

require 'test_helper'
class BreadcrumbTest < ActionController::TestCase

  test "Throws token required error" do
    @controller = BreadcrumbTestsController.new( :index ) { render :nothing => true }

    with_routing do |set|
      set.draw do
        resources :breadcrumb_tests
      end

      begin
        get :index
        assert_response :success
      end

    end
  end
end

class BreadcrumbTestsController < ActionController::Base
  include BreadcrumbList

  def initialize(method_name, &method_body)
    self.class.send(:define_method, method_name, method_body)
  end

end

...但我无法解释为什么会这样。