Skip to main content

_ruby

TL;DR - Show Me The Code

1-upload-a-file/code/ruby/upload.rb
require 'selenium-webdriver'
require 'rspec/expectations'
include RSpec::Matchers

def setup
@driver = Selenium::WebDriver.for(:firefox)
end

def teardown
@driver.quit
end

def run
setup
yield
teardown
end

run do
filename = 'some-file.txt'
file = File.join(Dir.pwd, filename)
@driver.get('https://the-internet.herokuapp.com/upload')
@driver.find_element(id: 'file-upload').send_keys(file)
@driver.find_element(id: 'file-submit').click
uploaded_filename = @driver.find_element(id: 'uploaded-files').text

expect(uploaded_filename).to eq(filename)
end

Code Walkthrough

Importing Libraries

Lines 1 to 3 are pulling in our requisite classes (e.g., selenium-webdriver to drive the browser, and rspec/expectations & RSpec::Matchers for our assertion).

Setup and Teardown

Lines 5 to 11 are setting up and tearing down the browser instance. We're using the setup method to launch a new instance of Firefox with Selenium and storing it in a class variable that we'll use throughout all tests. After our test executes the teardown method will execute. This calls driver.quit() which ends the session by closing the browser instance.

The run method is a custom method that we've defined to execute our test. It's a simple wrapper around the setup and teardown methods. We're using it to keep our test code clean and easy to read.

The Test

Lines 18 to 28 are the test itself.

After specifying the filename we get the full path to the file (which we're doing with File.join(Dir.pwd, filename)). This approach assumes that the file is living in the same directory as the test script.

Next we visit the page with the upload form, input the file text (e.g., the full path to the file plus the filename with it's extension), and submit the form. After the file is uploaded the page will display the filename that it just processed. We use this text to perform our assertion (making sure the uploaded file is what we expect).

Executing the Test

Before executing the test, we need to make sure the required dependencies are declared on the Gemfile file.

Toggle to see the Gemfile file.
1-upload-a-file/code/ruby/Gemfile
source 'https://rubygems.org'

gem 'rspec', '~> 3.10'
gem 'selenium-webdriver', '~> 4.26.0'

Finally, we can run the test by executing ruby upload.rb from the command-line.