我目前正在尝试使用rspec测试自定义Devise会话控制器。我的控制器看起来像这样:
class SessionsController < Devise::SessionsController
def create
#valid email?
if !(params[:email] =~ /^[A-Za-z0-9._%+-]+@[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".
即使在继承控制器中遗漏了create方法,也会出现错误。该错误不会出现在get:new上。它似乎是post:仅创建。 我没有想法?有帮助吗? 谢谢!
答案 0 :(得分: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
不确定你的双重渲染问题,你确定你应该调用post:create然后渲染吗?我不确定rspec应该如何工作。