2014-11-08 84 views
1

我正在构建一个Rails 4引擎,它提供了一些控制器和模型,然后将被我们的几个应用程序使用。我正在编写或编写单元测试,并且在制作redirect_to的控制器中遇到问题。Rails 4引擎控制器重定向失败单元测试

在,我测试控制器,我有下列行为:

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

回答

2

你应该能够解决这个问题使用:

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

此外,寻找出日志中的取消通知,由于使用use_route这是这样的:

DEPRECATION WARNING: Passing the use_route option in functional tests are deprecated. Support for this option in the process method (and the related get , head , post , patch , put and delete helpers) will be removed in the next version without replacement. Functional tests are essentially unit tests for controllers and they should not require knowledge to how the application's routes are configured. Instead, you should explicitly pass the appropiate params to the process method. Previously the engines guide also contained an incorrect example that recommended using this option to test an engine's controllers within the dummy application. That recommendation was incorrect and has since been corrected. Instead, you should override the @routes variable in the test case with Foo::Engine.routes . See the updated engines guide for details.

+0

,什么时当我找到它时,我应该使用这个弃用通知吗? ;-) – CJBrew 2015-03-08 11:13:33

+0

@CJBrew:切换到使用新推荐的方式,在测试中设置一个'@ routes'实例变量。 – 2015-03-17 00:33:32

+0

是的,我在这里找到答案:http://www.relishapp.com/rspec/rspec-rails/v/3-2/docs/controller-specs/engine-routes-for-controllers – CJBrew 2015-03-17 19:26:45