我正在阅读 Michael Hartl 的 Rails 教程。我下载了源代码samle_app_rails_4。然后我添加了一个用于注销用户的测试,它在我的浏览器中运行良好,但在 Rspec 中,它失败了。我没有对源代码进行任何更改,而是将其添加到user_pages_spec.rb
.
require 'spec_helper'
describe "User pages" do
describe "sign out" do
let(:user) { FactoryGirl.create(:user) }
before :each do
sign_in user
end
it "should sign out a user" do
delete signout_path
expect(page).to have_content("Sign in")
end
end
end
该sign_in
方法定义在spec/support/utilities.rb
include ApplicationHelper
def sign_in(user, options={})
if options[:no_capybara]
# Sign in when not using Capybara as well.
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
sessions_controller.rb
是这样的(我在这里忽略了创建操作。)
class SessionsController < ApplicationController
def new
end
def destroy
sign_out
redirect_to root_url
end
end
是这样sessions_helper.rb
的:
module SessionsHelper
def sign_in(user)
remember_token = User.new_remember_token
cookies.permanent[:remember_token] = remember_token
user.update_attribute(:remember_token, User.encrypt(remember_token))
self.current_user = user
end
def signed_in?
!current_user.nil?
end
def current_user=(user)
@current_user = user
end
def current_user
remember_token = User.encrypt(cookies[:remember_token])
@current_user ||= User.find_by(remember_token: remember_token)
end
def current_user?(user)
user == current_user
end
def sign_out
self.current_user = nil
cookies.delete(:remember_token)
end
end
我尝试了很多解决方案,在 github 上发布了一个问题,并且这个Cookies do not persist in Rspec on rails 3.1
我也经历了这些问题,但没有任何帮助。https://stackoverflow.com/questions/tagged/railstutorial.org。
我什至升级了我的 rspec 和 capybara gem。也许我的测试文件有问题?
delete signout_path
不适合注销用户?我发现在示例应用程序中很奇怪,当用户登录后,他仍然可以访问 signin_path 和 signup_path。
希望有人可以帮助我,非常感谢!