2014-11-08 99 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