我目前正在尝试使用 rspec 测试自定义设计 session Controller 。我的 Controller 看起来像这样:
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 Controller 测试是这样的:
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 的提示没有解决这个问题。谢谢你的帮助。
添加
我进一步调查。我实际上能够通过在 Controller 规范中添加以下内容来“删除”错误:
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".
即使在继承 Controller 中省略了 create 方法,也会出现错误。例如,错误不会出现在 get :new 上。它似乎是 post :create only。
我没有想法?有什么帮助吗?
谢谢!
最佳答案
我终于解决了我的问题,包括设计测试助手,在我的测试中调用方法 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 应该如何工作。
关于ruby-on-rails - 自定义设计 session Controller 的 RSpec 测试因 AbstractController::ActionNotFound 而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4291755/