Half-Penny For Your Thoughts

rounded down to the nearest cent



Categories


Recent Articles




Computing

Selenium with Rails

This past week, I’ve started using Selenium for integration testing of a Rails application. Writing the tests was pretty simple, thanks to the IDE, but setting them up to run using rake took me a bit. If you want the rake file, skip down a bit; first a few of the resources I found and comments thereon.

Okay, then, the post in “Steve’s Blog” got me to where I could run tests, but I finessed my Rake file a bit. My particular goal was to be able to run Selenium in a specific browser based on the rake task, and to have a task that runs several browsers.

namespace :selenium do

  desc 'Run Selenium java server'
  task :server do
    # dir would change based on where the selenium-server is located
    dir = "c:\\path\\to\\server"
    `java -jar "#{dir}selenium-server.jar"`
  end

  BROWSERS = %w{ie iexplore firefox safari opera}

  desc 'Run selenium tests in all major browsers'
  task :all do
    errors = %w(selenium:iexplore selenium:firefox selenium:safari selenium:opera).collect do |task|
      puts task.upcase
      begin
        Rake::Task[task].invoke
        nil
      rescue => e
        task
      end
    end.compact
    abort "Errors running #{errors.to_sentence}!" if errors.any?
  end

  # Create task for running tests in each browser
  BROWSERS.each do | browser |
    Rake::TestTask.new(browser.to_sym => "db:test:prepare") do |t|
      # t.options add the browser to ARGV to the test file.
      t.options = ["-- #{browser}"]
      t.libs << "test"
      t.pattern = 'spec/selenium/**/*_test.rb'
      t.verbose = true
    end
    Rake::Task["selenium:#{browser}"].comment =
      "Run selenium tests in #{browser}"
  end

end

In the test_helper.rb file, I added this to set a global $browser variable:

$browser = ARGV[0] || "iexplore"

$browser = "iexplore" if "ie" == $browser # because I'd rather just type "ie"

And, finally, in the test files:

# Server and URL settings may vary.
@selenium = Selenium::SeleneseInterpreter.new("localhost", 4444, "*#{$browser}", "http://localhost:4445", 10000);

blog comments powered by Disqus