我正在实现一种“懒惰登录”功能。我的cucumber测试应该描述如下:
Feature: User log in
Scenario: Lazy login
Given I didn't log out the last time I was on the site
When I go to the homepage
Then I should automatically be logged in
以下是我的步骤定义:
Given(/^I didn't log out the last time I was on the site$/) do
user = FactoryGirl.create(:user)
visit new_user_session_path
fill_in('user[email]', with: user.email)
fill_in('user[password]', with: 'test123')
click_button('Sign in')
Capybara.reset_sessions!
end
When(/^I go to the homepage$/) do
visit root_path
end
Then(/^I should automatically be logged in$/) do #<-- Fails here
page.should have_content("Logout")
end
当用户登录时,会设置
cookies.signed [:auth_token]
。应用程序控制器中的一个前置过滤器将使用此标记,以使开启新浏览器的用户自动登录。class SessionsController < Devise::SessionsController
def create
super
if user_signed_in?
puts 'yesssssss'
session[:user_id] = current_user.id
current_user.remember_me! if current_user.remember_token.blank?
cookies.signed[:auth_token] = {
:value => current_user.remember_token,
:domain => "mysite.com",
:secure => !(Rails.env.test? || Rails.env.development?)
}
puts "current_user.remember_token = #{current_user.remember_token}"
puts 'cookies:'
puts cookies.signed[:auth_token]
end
end
这是我 ApplicationController 中的 before 过滤器:
end
def sign_in_through_cookie
logger.info "logging in by cookie"
puts "logging in by cookie"
puts cookies.signed[:auth_token] #<-- PROBLEM: this returns nil.
return true if !current_user.nil?
if !cookies[:auth_token].nil? && cookies[:auth_token] != ''
user = User.find_by_remember_token(cookies.signed[:auth_token])
return false if user.blank?
sign_in(user)
puts 'success'
return true
else
return false
end
end
问题在于,在我的cucumber功能的最后一步中,cookies.signed [:auth_token]
返回nil。我猜这只是capybara的一个问题。所以,我是否实际上必须在测试中设置一个cookie,而不是使用控制器中的cookie?
Capybara.current_session.driver.request.cookies['auth_token']
,而不是Capybara.current_session.driver.request.cookies.[]('auth_token')
? - Arepopage.driver.set_cookie()
,它有3个参数:cookie的名称、其值以及用于设置其他内容的选项哈希,包括cookie的到期值。 - sameersundefined method set_cookie for #<Selenium::WebDriver::Chrome::Driver:
那么你可以这样设置cookies:page.driver.browser.manage.add_cookie(name: "cookie_name", value: "cookie_value")
- anandvc