ruby-on-rails-4environment-variablesmechanizefigaro-ruby

Rails 4, Mechanize, Figaro: environment variables not working in form


I'm attempting to log in to a website but my env variables are not inserting properly in the necessary form. I am using Figaro and my environment variables are safely stored in config/application.yml. I can confirm two things...

  1. When hard-coding my actual email and password, I am able to log in successfully
  2. My environment vars return properly when testing in the Rails console (e.g. ENV["WHATEVER"] returns the proper value)

    # app/helpers/scrape_wf.rb
    
    require 'mechanize'
    
    agent = Mechanize.new
    page = agent.get('https://www.wealthfront.com/login')
    login_form = page.forms.first
    
    # LOG IN UNSUCCESSFUL
    
    login_form.email    = ENV["WF_EMAIL"] 
    login_form.password = ENV["WF_PASSWORD"]
    
    home_page = login_form.submit
    
    puts page.title          # => Log In to Wealthfront
    puts home_page.title     # => Log In to Wealthfront
    
    # LOG IN SUCCESSFUL
    
    login_form.email    = "my_harcoded_email"
    login_form.password = "my_harcoded_password"
    
    home_page = login_form.submit
    
    puts page.title          # => Log In to Wealthfront
    puts home_page.title     # => Wealthfront
    

and in the console...

    rails c
    Loading development environment (Rails 4.2.4)
    [1] pry(main)> ENV["WF_EMAIL"]
    => "my_harcoded_email"
    [2] pry(main)> ENV["WF_PASSWORD"]
    => "my_harcoded_password"

What am I doing wrong...?


Solution

  • According to this excellent post...

    When you install the Figaro gem in your Rails app, any values that you enter into config/application.yml will be loaded into the ruby ENV hash on startup.

    ...since I am developing the script and running it from the command line (i.e. ruby such_and_such.rb) my environment variables are not being set/initialized and hence they are blank when the script executes.

    Solution: Print scrape results to a view (which, confirmed, does work) rather than console.