Using Default Parameter Values in Automated E2E Test Scripts with Ruby
Using Ruby default parameter in your E2E test scripts can make your scripts more readable.
Below is an example of a typical user login test implemented using Selenium WebDriver in Ruby.
it "User Login OK" do
driver.find_element(:id, "username").sendkeys("whenwise")
driver.find_element(:id, "password").sendkeys("test01")
driver.find_element(:input, "//input[@value='Sign in']").click
#...
end
Obviously, we are going to use these three test steps often in other tests. Following the Maintainable Automated Test Design, make it a reusable function (by invoking a “Extract Function” refactoring, which TestWise can do).
def login(username, password)
driver.find_element(:id, "username").sendkeys(username)
driver.find_element(:id, "password").sendkeys(password)
driver.find_element(:input, "//input[@value='Sign in']").click
end
it "User Login OK" do
login("whenwise", "test01")
#...
end
it "User Login OK failed with a wrong password" do
login("whenwise", "tryluck")
#...
end
it "Other User Login OK" do
login("buildwise", "test01")
#...
end
it "Another User Login OK" do
login("testwise", "test01")
#...
end
# ...
The script is now more readable and, more importantly, easier to maintain. Typically, I follow up with a “Move to Helper” refactor to make this function reusable across all test scripts.
Typically, the passwords for many test users are identical, often set to something like “test01
”. Some testers may prefer the following test script style, as it enhances readability.
it "User Login OK" do
login("whenwise")
#...
end
it "Other User Login OK" do
login("buildwise")
#...
end
it "Another User Login OK" do
login("testwise")
#...
end
This is easy to achieve in Ruby: add a default value for the password
parameter.
def login(username, password="test01")
driver.find_element(:id, "username").sendkeys(username)
driver.find_element(:id, "password").sendkeys(password)
driver.find_element(:input, "//input[@value='Sign in']").click
end
This means the second argument, password
, is optional. If not specified, it will use the default value: test01
.
The following two uses of this login
function are both OK: with one parameter and two parameters.
it "User Login OK" do
login("whenwise")
#...
end
it "User Login OK failed with a wrong password" do
login("whenwise", "tryluck")
#...
end
While the above example is simple, it showcases an important concept in E2E Test Automation: Improving the quality of test scripts without introducing breaking changes.
I will explain more in another (upcoming) article: “Extending Function Behaviour with Optional Parameters in Automated E2E Ruby Scripts”.
Related reading: