2010-11-27 112 views
16

我目前正在尝试使用rspec测试自定义设计会话控制器。我的控制器看起来是这样的:自定义设计会话控制器RSpec测试失败AbstractController :: ActionNotFound

class SessionsController < Devise::SessionsController 

    def create 
    #valid email? 
    if !(params[:email] =~ /^[A-Za-z0-9._%+-][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,}$/) 
     set_flash_message :notice, "Please enter a valid e-mail address!" 
    end 

    super 
    end 
end 

我的RSpec的控制器测试是这样的:

require 'spec_helper' 
require 'devise/test_helpers' 

describe SessionsController do 

    it "should put a warning on invalid mail address login attempt" do 
    post :create, :user => {:email => 'invalidEmailAddress'} 
    response.should contain "Please enter a valid e-mail address!" 
    end 

    it "should put no warning on valid mail address login attempt" do 
    pending 
    end 
end 

如果我执行RSpec的测试失败与以下行:从

Failure/Error: post :new, :user => {:email => 'invalidEmailAddress'} 
    AbstractController::ActionNotFound 
    # ./spec/controllers/sessions_controller_spec.rb:7 

提示plataformatec Devise Wiki以及this post没有解决这个问题。谢谢你的帮助。

加成

我进一步调查。实际上,我是能够“删除”错误与下列除了控制器规格:

before(:each) do 
    request.env['devise.mapping'] = Devise.mappings[:user] 
end 

但现在出现一个新的错误:

Failure/Error: post :create #currently fails with multiple render warning 
Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return". 

即使在创造方法的继承冷落控制器出现错误。该错误不会出现在get:new中。它似乎是后:只创建。 我不知道?任何帮助? 谢谢!

回答

18

我终于修复了我的问题,包括设计测试助手,在我的测试中调用方法setup_controller_for_warden并执行request.env [“devise.mapping”] = Devise.mappings [:user]。像这样:

require 'test_helper' 

class SessionsControllerTest < ActionController::TestCase 
    include Devise::TestHelpers 

    test "should reject invalid captcha" do 
     setup_controller_for_warden 
     request.env["devise.mapping"] = Devise.mappings[:user] 

     get :new 

     assert_response :success 
    end 
end 

不知道你的双渲染问题,但你确定你应该调用后:创建然后渲染?我不确定rspec应该如何工作。

+0

`render`是针对视图规范的 - 它在控制器规范中没有任何意义,默认情况下它不会呈现视图。如果您希望测试控制器进行渲染,有一个`render_views`指令(替换旧的“integrate_views”)。 – zetetic 2010-12-01 04:50:28