我正在使用Rspec来测试控制器行为。当用户访问未经授权的页面时,他们将重定向到root_url,并按照我的cancan(gem)救援区中的说明发送“您未经授权”消息:
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_url, alert: exception.message
end
我现在要测试将它们重定向到root_url,并且响应中包含消息“您无权访问此页面”。 但是,测试失败:
expected: "http://test.host/"
got: "http://test.host/users/sign_in"
另一个失败:
expected "<html><body>You are being <a href=\"http://test.host/users/sign_in\">redirected</a>.</body></html>" to include "You are not authorized to access this page."
这些是规格:
require 'rails_helper'
describe CodesController, type: :controller do
login_user
describe "Get index" do
it 'denies access to marketing user' do
get :index
expect(response.status).to be == 302
end
it 'redirects user to home page' do
get :index
expect(response.location).to eq(root_url)
end
it 'alerts user of unauthorized access' do
get :index
expect(response.body).to include('You are not authorized to access this page.')
end
end
end
第一个测试通过。后两个失败。但是,当我以市场营销用户身份登录网站时,它不会将我重定向到sign_in页面。如CanCan块所示,它转到root_path。我对Rspec测试中的响应对象不了解什么?
这是login_user的来源:
module ControllerMacros
def login_user
before :example do
@request.env["devise.mapping"] = Devise.mappings[:user]
marketing = create :marketing
sign_in marketing
end
end
end
rails_helper.rb:
config.extend ControllerMacros, type: :controller
我正在使用:
rspec-rails 3.8.0
devise 4.5.0
rails 4.2.10
答案 0 :(得分:0)
更新:您不需要第三次测试,因为那是视图逻辑而不是控制器,并且警报应该在导轨中按预期工作。但是,您只需要测试是否已按预期进行重定向。试试这个:
require 'rails_helper'
describe CodesController, type: :controller do
login_user
describe "Get index" do
subject { get :index }
it 'denies access to marketing user' do
subject
expect(response.status).to be == 302
end
it 'redirects user to home page' do
expect(subject).to redirect_to(root_url)
end
end
end