为什么RSPEC在Rails 5.2的Edit视图和New视图测试中表现不同



我正在使用Rails 5.2开发一个应用程序,并使用Capybara测试这些功能。

我想确保未连接的用户不能查看游乐场页面,而连接的用户可以。身份验证基于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

但它并没有告诉我用户是否真的登录了页面。。。

还有一个细节:当一个未连接的用户试图访问此新视图时,他实际上会登录到登录页面!

你能解释一下为什么新观点的行为不同,以及如何解决这个问题吗?

非常感谢!

我终于发现方法new_playground_path不需要任何参数。

我删除了(pg(表达式,这最终解决了问题。

解决了!

最新更新