使用 Capybara 提供的一些方法进行登录,比如
fill_in "Email", with: user.email
fill_in "Password", with: user.password
click_button "Sign in"
这个跟在浏览器里手动填表然后点击“Sign in”有什么区别?
更新一下问题。 问题来自于 Rails Tutorial 里的 Sample App。 http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-users#sec-requiring_signed_in_users
spec/requests/authentication_pages_spec.rb 文件
require 'spec_helper'
describe "Authentication" do
.
.
.
describe "authorization" do
.
.
.
describe "as wrong user" do
let(:user) { FactoryGirl.create(:user) }
let(:wrong_user) { FactoryGirl.create(:user, email: "[email protected]") }
before { sign_in user, no_capybara: true }
describe "visiting Users#edit page" do
before { visit edit_user_path(wrong_user) }
it { should_not have_title(full_title('Edit user')) }
end
describe "submitting a PATCH request to the Users#update action" do
before { patch user_path(wrong_user) }
specify { expect(response).to redirect_to(root_url) }
end
end
end
end
spec/support/utilities.rb
def sign_in(user, options = {})
if options[:no_capybara]
# Sign in when not using Capybara
remember_token = User.new_remember_token
cookies[:remember_token] = remember_token
user.update_attribute(:remember_token, User.encrypt(remember_token))
else
visit signin_path
fill_in "Email", with: user.email
fill_in "Password", with: user.password
click_button "Sign in"
end
end
暂时先无视原文里 FactoryGirl 的错误,这个不是问题的所在。
把 before { sign_in user, no_capybara: true }
换成 before { sign_in user }
,
浏览器里跳转是正常的,会跳到 root_url,
但是 rspec 里会有这样的错误
Failures:
1) AuthenticationPages authorization as wrong user submitting a PATCH request to the Users#update action Failure/Error: specify { expect(response).to redirect_to(root_url) } Expected response to be a redirect to http://www.example.com/ but was a redirect to http://www.example.com/signin. Expected "http://www.example.com/" to be === "http://www.example.com/signin". # ./spec/requests/authentication_pages_spec.rb:85:in `block (5 levels) in '
Finished in 5.81 seconds 76 examples, 1 failure, 3 pending