在Michael Hartl 的 Rails 教程 (Rails 3.2)中,在清单 9.52 中:
describe "when signing in again" do
before do
delete signout_path
print page.html <---- Insert this here
visit signin_path
print page.html <---- Insert here again
fill_in "Email", with: user.email
fill_in "Password", with: user.password
click_button "Sign in"
end
it "should render the default (profile) page" do
page.should have_selector('title', text: user.name)
end
end
我插入了那两张照片。而且,令人惊讶的是,我得到了同一页面的打印输出(不应该,它应该在发送请求后将您带回根 url DELETE
)。发生这种情况后,由于visit signin_path
将我带回登录页面,因此登录过程成功,测试用例也成功。但是,第二个print page.html
给了我仍然登录的用户的标题。
当我更改delete signout_path
为 时click_link "Sign out"
,它起作用了。
我是否遗漏了代码中的某些内容或者它是 Capybara 错误?(因为我很确定我遵循的一切都恰到好处..)
更新:
如果我更改delete signout_path
它Capybara.current_session.driver.delete signout_path
也可以正常工作。(意思是 capybara 正确退出用户)
更新
这些是文件(会话控制器和助手):
session_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
sign_in user
redirect_back_or user
else
flash.now[:error] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
sign_out
redirect_to root_url
end
end
session_helper.rb
module SessionsHelper
def sign_in(user)
cookies.permanent[:remember_token] = user.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?(user)
user == current_user
end
def signed_in_user
unless signed_in?
store_location
redirect_to signin_url, notice: "Please sign in."
end
end
def current_user
@current_user ||= User.find_by_remember_token(cookies[:remember_token])
end
def sign_out
self.current_user = nil
cookies.delete(:remember_token)
end
def redirect_back_or(default)
redirect_to(session[:return_to] || default)
session.delete(:return_to)
end
def store_location
session[:return_to] = request.url
end
end
路线.rb
DemoApp::Application.routes.draw do
...
root to: 'static_pages#home'
match '/signup', to: 'users#new'
match '/signin', to: 'sessions#new'
match '/signout', to: 'sessions#destroy', via: :delete
resources :sessions, only: [:new, :create, :destroy]
...
end