简体   繁体   中英

Cookies within a cucumber test using capybara

As part of my integration tests for a website I am using cucumber with capybara. It seems that capybara cannot emulate the use of cookies.

For example I set the cookie when the user signs in:

    def sign_in(user)
      cookies.permanent.signed[:remember_token] = [user.id, user.salt]
      current_user = user
    end

However when I later fetch the value of cookies using cookies.inspect it returns {} Is this a known limiting of capybara? How can I test a signed in user over multiple requests if this is the case?

I should add my test:

Scenario: User is signed in when they press Sign In
 Given I have an existing account with email "bob@jones.com" and password "123456"
 And I am on the signin page
 When I fill in "Email" with "bob@jones.com"
 And I fill in "Password" with "123456"
 And I press "Sign In"
 Then I should see "Welcome Bob Jones"

Here's a step that works for me. It sets a cookie "admin_cta_choice" to be equal to a model id derived from the input value.

Given /I have selected CTA "([^"]+)"/ do |cta_name|
  cta = Cta.find_by_name(cta_name)
  raise "no cta with name '#{cta_name}'" if cta.nil?

  k = "admin_cta_choice"
  v = cta.id

  case Capybara.current_session.driver
  when Capybara::Poltergeist::Driver
    page.driver.set_cookie(k,v)
  when Capybara::RackTest::Driver
    headers = {}
    Rack::Utils.set_cookie_header!(headers,k,v)
    cookie_string = headers['Set-Cookie']
    Capybara.current_session.driver.browser.set_cookie(cookie_string)
  when Capybara::Selenium::Driver
    page.driver.browser.manage.add_cookie(:name=>k, :value=>v)
  else
    raise "no cookie-setter implemented for driver #{Capybara.current_session.driver.class.name}"
  end
end

here's a nice way to show the content of the cookies while running your feature

https://gist.github.com/484787

Why don't you just run the test with selenium? Just add @selenium tag before the scenario you want to run with a real browser. :)

That gist didn't work for me as of date of this posting, however this does, and is somewhat simpler:

http://collectiveidea.com/blog/archives/2012/01/05/capybara-cucumber-and-how-the-cookie-crumbles/

Capybara doesn't have an API for reading and setting cookies.

However, you can simulate logging in with Capyabara very easily - just visit the login link. That will log you in, including setting all cookies for you.

To see this in action, just look at my example Rails app .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM