簡體   English   中英

Rails + Cucumber/Capybara:如何在測試中設置/檢索 cookie?

[英]Rails + Cucumber/Capybara: How to set/retrieve cookies in tests?

我正在實現一個懶惰的登錄功能。 我的黃瓜功能應該描述它:

    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]被設置。 這將由我的 ApplicationController 中的 before 過濾器使用,以便打開新瀏覽器的用戶將自動登錄:

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 過濾器:

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

所以問題是在我的黃瓜功能的最后一步, cookies.signed[:auth_token]返回 nil。 我猜這只是水豚的事情。 那么我真的必須在測試中設置一個 cookie 而不是在我的控制器中使用一個嗎?

所以最終我在嘗試了很多不同的事情后想通了。

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.current_session.driver.request.cookies.[]('auth_token').should_not be_nil
  auth_token_value = Capybara.current_session.driver.request.cookies.[]('auth_token')
  Capybara.reset_sessions!
  page.driver.browser.set_cookie("auth_token=#{auth_token_value}")
end

When(/^I go to the homepage$/) do
  visit root_path
end

Then(/^I should automatically be logged in$/) do
  page.should have_content("Logout")
end

更新:

這是我在使用 Selenium 進行某些測試時使用的內容:

if Capybara.current_session.driver.class == Capybara::Selenium::Driver
  auth_token = page.driver.browser.manage.cookie_named('auth_token')[:value]
  page.driver.browser.manage.delete_all_cookies
  page.driver.browser.manage.add_cookie(:name => "auth_token", :value => auth_token)
else
  puts "cookies = #{Capybara.current_session.driver.request.cookies}"
  Capybara.current_session.driver.request.cookies.[]('auth_token').should_not be_nil
  auth_token_value = Capybara.current_session.driver.request.cookies.[]('auth_token')
  Capybara.reset_sessions!
  page.driver.browser.set_cookie("auth_token=#{auth_token_value}")
end

使用封裝驅動程序方法的https://github.com/nruth/show_me_the_cookies 它有獲取 cookie 的方法,刪除 cookie 的方法,以及創建 cookie 的方法,稱為create_cookie

我只需要測試 cookie 值

靈感來自https://collectiveidea.com/blog/archives/2012/01/05/capybara-cucumber-and-how-the-cookie-crumbles

並移植到 Rails 5.x

創建features/support/cookies.rb

有內容

module Capybara
  class Session
    def cookies
      @cookies ||= ActionDispatch::Request.new(Rails.application.env_config.deep_dup).cookie_jar
    end
  end
end

Before do
  allow_any_instance_of(ActionDispatch::Request).to receive(:cookie_jar).and_return(page.cookies)
  allow_any_instance_of(ActionDispatch::Request).to receive(:cookies).and_return(page.cookies)
end

然后是測試步驟

Then('is set cookie {string} with value {string}') do |cookie, value|
  expect(page.cookies.signed[cookie]).to eq value
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM