Skip to content

Instantly share code, notes, and snippets.

@pomeo
Forked from Najaf/mechanize-cheat-sheet.rb
Created August 23, 2014 05:46
Show Gist options
  • Save pomeo/dda9ea7b49062a5f4fd6 to your computer and use it in GitHub Desktop.
Save pomeo/dda9ea7b49062a5f4fd6 to your computer and use it in GitHub Desktop.

Revisions

  1. @Najaf Najaf revised this gist Nov 8, 2013. 1 changed file with 3 additions and 0 deletions.
    3 changes: 3 additions & 0 deletions mechanize-cheat-sheet.rb
    Original file line number Diff line number Diff line change
    @@ -4,6 +4,9 @@
    # Visit a web page
    agent.get 'http://localhost:3000/'

    # get the url of the current page
    agent.page.uri #=> http://localhost:3000

    # agent remembers the scheme + host, so no need to supply it when navigating somewhere else
    agent.get '/whatever'

  2. @Najaf Najaf revised this gist Nov 4, 2013. 1 changed file with 15 additions and 1 deletion.
    16 changes: 15 additions & 1 deletion mechanize-cheat-sheet.rb
    Original file line number Diff line number Diff line change
    @@ -31,4 +31,18 @@
    c.path = '/'
    end

    agent.cookie_jar.add(agent.history.last.uri, cookie)
    agent.cookie_jar.add(agent.history.last.uri, cookie)

    # Make it a little DSL-ish with instance_eval if you like...
    Mechanize.new.instance_eval do
    get 'http://localhost:3000'
    page.link_with(text: 'Sign up').click
    page.forms.first.tap do |f|
    f['user[email]'] = '[email protected]'
    f['user[password]'] = '123456789'
    f['user[password_confirmation]'] = '123456789'
    f.submit
    end
    end

    end
  3. @Najaf Najaf created this gist Nov 4, 2013.
    34 changes: 34 additions & 0 deletions mechanize-cheat-sheet.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    # Initialize Mechanize Agent
    agent = Mechanize.new

    # Visit a web page
    agent.get 'http://localhost:3000/'

    # agent remembers the scheme + host, so no need to supply it when navigating somewhere else
    agent.get '/whatever'

    # Click on a link with the given text
    agent.page.link_with(text: "Click here").click

    # Complete and submit the first form on the page
    agent.page.forms.first.tap do |f|
    f['user[email]'] = '[email protected]'
    f['user[password]'] = '123456789'
    f['user[password_confirmation]'] = '123456789'
    f['a_field[that_wasnt_in_the_form]'] = 'sneaky value'
    f.submit
    end

    # Inspect the page body
    puts agent.page.body.inspect

    # Search for elements on the page
    puts agent.page.search('.secret').text.strip

    # Set a cookie
    cookie = Mechanize::Cookie.new('key', 'value').tap do |c|
    c.domain = 'localhost:3000'
    c.path = '/'
    end

    agent.cookie_jar.add(agent.history.last.uri, cookie)