我使用Rspec来测试控制器的行为。当用户访问未经授权的页面时,他们将重定向到根url并传递消息“you are authorized”(您未经授权),如my cancan(gem)rescue block中所指定:
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_url, alert: exception.message
end
但是,测试失败:
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
这是登录用户的来源:
module ControllerMacros
def login_user
before :example do
@request.env["devise.mapping"] = Devise.mappings[:user]
marketing = create :marketing
sign_in marketing
end
end
end
config.extend ControllerMacros, type: :controller
我正在使用:
rspec-rails 3.8.0
devise 4.5.0
rails 4.2.10