我正在使用Rails 5.2开发应用程序,并使用Capybara测试功能。
我想确保未连接的用户无法查看Playgrounds页面,而已连接的用户可以查看。身份验证基于Devise,因此,当您请求未经授权的页面时,会将您路由到登录页面。
我编写了此测试:spec / features / playgrounds_spec.rb
require 'rails_helper'
RSpec.describe Playground, type: :request do
include Warden::Test::Helpers
describe "Playground pages: " do
let(:pg) {FactoryBot.create(:playground)}
context "when not signed in " do
it "should propose to log in when requesting index" do
get playgrounds_path
follow_redirect!
expect(response.body).to include('Sign in')
end
it "should propose to log in when requesting new" do
get new_playground_path(pg)
follow_redirect!
expect(response.body).to include('Sign in')
end
it "should propose to log in when requesting edit" do
get edit_playground_path(pg)
follow_redirect!
expect(response.body).to include('Sign in')
end
it "should propose to log in when requesting show" do
get playground_path(pg)
follow_redirect!
expect(response.body).to include('Sign in')
end
end
context "when signed in" do
before do
get "/users/sign_in"
test_user = FactoryBot.create(:user)
login_as test_user, scope: :user
end
it "should display index" do
get playgrounds_path
expect(response).to render_template(:index)
end
it "should display new view" do
get new_playground_path(pg)
expect(response).to render_template(:_form)
end
it "should display edit view" do
get edit_playground_path(pg)
expect(response).to render_template(:_form)
end
it "should display show view" do
get playground_path(pg)
expect(response).to render_template(:show)
end
end
end
end
测试应该成功,但是失败并出现以下错误:
.F....#<Playground:0x000000000d119470>
.#<Playground:0x000000000e059700>
.
Failures:
1) Playground Playground pages: when not signed in should propose to log in when requesting new
Failure/Error: follow_redirect!
RuntimeError:
not a redirect! 401 Unauthorized
# ./spec/features/playgrounds_spec.rb:17:in `block (4 levels) in <top (required)>'
Finished in 4.81 seconds (files took 12.28 seconds to load)
8 examples, 1 failure
Failed examples:
rspec ./spec/features/playgrounds_spec.rb:15 # Playground Playground pages: when not signed in should propose to log in when requesting new
为了解决这个问题,我可以简单地测试请求返回到新视图的状态:
it "should propose to log in when requesting new" do
get new_playground_path(pg)
#follow_redirect!
expect(response.status).to eq 401
end
但是它不会告诉我用户是否真的登陆了登录页面...
一个更多详细信息:当一个未连接的用户尝试访问此新视图时,他实际上已登录到登录页面!
您能否解释一下为什么新视图的行为不同,以及如何解决此问题?
非常感谢!
我正在使用Rails 5.2开发应用程序,并使用Capybara测试功能。我想确保未连接的用户无法查看Playgrounds页面,而已连接的用户可以查看。 ...
我终于发现方法new_playground_path不需要任何参数。