【问题标题】:Rails 4 engine controller redirect fails unit testingRails 4引擎控制器重定向失败单元测试
【发布时间】:2014-11-08 18:40:25
【问题描述】:

我正在构建一个 Rails 4 引擎,它提供一些控制器和模型,然后我们的几个应用程序将使用它们。我正在编写单元测试或编写单元测试,但我在控制器中的操作遇到问题,这些操作会生成 redirect_to

在我正在测试的控制器中,我有以下操作:

def index
end

def new
  @block = GlobalIpBlock.new
end

def create
  @block = GlobalIpBlock.new(create_params)
  if @block.save
    flash[:success] = "The IP has been successfully blocked."
    redirect_to action: 'index'
  else
    render 'new'
  end
end

在控制器测试中我有这两个测试:

test "should get new block" do
  get :new, use_route: :watchdog
  assert_response :ok
  assert_not_nil assigns(:block)
end

test "should create global ip block" do
  assert_difference('GlobalIpBlock.count') do
    post :create, block: {some_param: 'some value'}, use_route: :watchdog
  end

  assert_redirected_to :index
end

第一个测试通过但第二个抛出错误:

ActionController::UrlGenerationError: No route matches {:action=>"index"}

我没有在引擎中创建路由,并且在虚拟测试应用程序的路由中它只安装引擎。这样做的原因是我希望托管应用程序为引擎的控制器/操作提供自己的路由。

不过,这似乎不是问题,因为new 操作的测试通过了。此外,我尝试通过以下方式在引擎中创建路线:

resources :global_ip_blocks, except: [:edit, :update]

但这没有帮助,在虚拟测试应用程序的路由中也没有这样做。

我猜redirect_to 没有找到路径,就像在测试中从 get/post 中删除 use_route: :watchdog 失败一样,但是我该如何解决呢?是否有一种类似于将单元测试告诉use_route: :watchdog 的全局方式?

【问题讨论】:

    标签: ruby-on-rails unit-testing rails-engines


    【解决方案1】:

    您应该可以使用以下方法解决此问题:

    class MyControllerTest < ActionController::TestCase
      def setup
        @routes = MyEngine::Engine.routes
      end
    end
    

    另外,请注意日志中因使用use_route 而导致的弃用通知,例如:

    弃用警告:不推荐在功能测试中传递use_route 选项。 process 方法(以及相关的 getheadpostpatchputputdelete 助手)中对此选项的支持将在下一版本中删除,无需替换。功能测试本质上是控制器的单元测试,它们不应该需要知道如何配置应用程序的路由。相反,您应该将适当的参数显式传递给 process 方法。以前,引擎指南还包含一个不正确的示例,建议使用此选项在虚拟应用程序中测试引擎的控制器。该建议不正确,现已更正。相反,您应该使用Foo::Engine.routes 覆盖测试用例中的@routes 变量。有关详细信息,请参阅更新的引擎指南。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    相关资源
    最近更新 更多