在控制器外测试重定向
Testing a redirect outside of a controller
我有一个辅助模块,如果当前用户没有访问网页的权限,redirect_to
会触发一个方法。
我在 运行 测试时遇到 NoMethodError
错误,因为助手实际上没有 redirect_to 方法。我试过像这样删除 redirect_to:
it "redirects the user to the user's langing page if the user doesn't have permission" do
allow(helper).to receive(:current_or_guest_user) { test_user }
expect(helper).to receive(:redirect_to)
helper.require_permission :view_admins
end
但是我收到一个很长的错误,说明助手没有实现 redirect_to
。
有没有办法杜绝这种方法?
您可以在您的规范中创建一个 anonymous
控制器并将您的模块包含在其中。当你得到它时,你可以像普通控制器一样测试它 action/method。所以,在你的规范中添加一些类似的东西:
controller(YourController) do
include YourModule
def index
render text: 'body'
end
end
我不知道你的方法是否是 before_action
,但看起来是,因为你正在测试用户是否具有所需的 view_admins
权限。
因此,当用户拥有所需的权限时,您的规范应该是这样的:
context 'when the user has the required permission' do
before do
# make sure the user has the required permission
end
it 'the user will see the rendered text' do
get :index
expect(response.body).to eq 'body'
end
end
当用户没有所需的权限时,他们将被重定向到您定义的路径。所以,像这样:
context 'when the user does NOT have the required permission' do
before do
# make sure the user does NOT have the required permission
end
it 'the user will be redirected to the specified path' do
get :index
expect(controller).to redirect_to your_specified_path
end
end
可以找到有关 anonymous
控制器的更多信息 here。
我有一个辅助模块,如果当前用户没有访问网页的权限,redirect_to
会触发一个方法。
我在 运行 测试时遇到 NoMethodError
错误,因为助手实际上没有 redirect_to 方法。我试过像这样删除 redirect_to:
it "redirects the user to the user's langing page if the user doesn't have permission" do
allow(helper).to receive(:current_or_guest_user) { test_user }
expect(helper).to receive(:redirect_to)
helper.require_permission :view_admins
end
但是我收到一个很长的错误,说明助手没有实现 redirect_to
。
有没有办法杜绝这种方法?
您可以在您的规范中创建一个 anonymous
控制器并将您的模块包含在其中。当你得到它时,你可以像普通控制器一样测试它 action/method。所以,在你的规范中添加一些类似的东西:
controller(YourController) do
include YourModule
def index
render text: 'body'
end
end
我不知道你的方法是否是 before_action
,但看起来是,因为你正在测试用户是否具有所需的 view_admins
权限。
因此,当用户拥有所需的权限时,您的规范应该是这样的:
context 'when the user has the required permission' do
before do
# make sure the user has the required permission
end
it 'the user will see the rendered text' do
get :index
expect(response.body).to eq 'body'
end
end
当用户没有所需的权限时,他们将被重定向到您定义的路径。所以,像这样:
context 'when the user does NOT have the required permission' do
before do
# make sure the user does NOT have the required permission
end
it 'the user will be redirected to the specified path' do
get :index
expect(controller).to redirect_to your_specified_path
end
end
可以找到有关 anonymous
控制器的更多信息 here。