Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined method 'set_cookie' for capybara How can I create a cookie?

I am running against a public site

When I try set_cookie I get:

undefined method 'set_cookie' for #<Selenium::WebDriver::Driver:0x531e792e4b07692c browser=:chrome>

require 'rspec'
require 'capybara'
require 'capybara/rspec'
require 'capybara/dsl'
require 'pry'

Capybara.run_server = false
Capybara.app_host = 'http://www.google.com/'

Capybara.register_driver :chrome do |app|
  Capybara::Selenium::Driver.new(app, :browser => :chrome)
end

root='/'

describe 'Form flow works', :type => :feature do

  before :each do
    Capybara.current_driver = :chrome
  end 

  it 'Collect the customer data', :happy do
    visit( root )
    page.driver.browser.set_cookie('test_disabled', 'true', :domain => 'www.google.com')

None of the current answers on SO address my issue or have worked.
Actual url is not google.

I tried show_me_cookies but that didn't work - details:
Added the gem: $ gem install show_me_the_cookies Successfully installed show_me_the_cookies-4.0.0 Parsing documentation for show_me_the_cookies-4.0.0 Done installing documentation for show_me_the_cookies after 0 seconds 1 gem installed

I added the following code to the spec (just using 1 file with all code right now)

RSpec.configure do |c| 
  c.treat_symbols_as_metadata_keys_with_true_values = true
  c.include ShowMeTheCookies, :type => :feature
end

and then i added show_me_the_cookies in my spec but all I got was ...spec/foo_spec.rb:17:inblock in ': uninitialized constant ShowMeTheCookies (NameError)`

like image 225
Michael Durrant Avatar asked Oct 28 '25 06:10

Michael Durrant


1 Answers

Capybara doesn't provide a cookie API because it's main aim is testing apps, and setting cookies when directly when testing is generally not a good idea. That being said, it sounds like you're scraping the web rather than testing so you have 2 options.

  1. Access the driver specific cookie methods. Since you're using the Selenium driver that would be something like

    page.driver.browser.manage.add_cookie(name: cookie_name, value: cookie_value)
    
  2. Use a gem that provides a common cookie API across different drivers. That would be the show_me_the_cookies gem recommended in the comments. That would then be

    create_cookie(cookie_name, cookie_value)
    

You may be getting uninitialized constant because you need to require 'show_me_the_cookies' in your spec_helper/rails_heper

like image 77
Thomas Walpole Avatar answered Oct 29 '25 21:10

Thomas Walpole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!