Assertions in Web Test Automation
Some common and useful assertions to use in your scripts
This article will cover some common assertions along with accompanying examples. I’ll use RSpec’s syntax in this article, but other frameworks will have the same or similar approach.
1. Verify the Page Source Contains a Piece of Text
This is the most basic assertion — checking the raw HTML source of the current page.
html = "Text assertion with a (<b>tab</b> before), and \n(new line before)!"
expect(driver.page_source).to include(html)RSpec uses to include for text present, and the opposite assertion of checking text is not there is not_to include.
expect(driver.page_source).not_to include(html)2. Verify an element’s text
This is the most common assertion I use. Instead of using driver.page_source, have the element’s locator’s text as the subject. In RSpec, use eq instead of include for exact matching.
expect(driver.find_element(:id, "label_1").text).to eq("First Label")If you are using JavaScript as the E2E scripting language, assert.equal( driver.findElement(By.id('span_1')).getText(), "...") does not work. You need to understand the Promise concept and use await instead.
await driver.findElement(By.id("span_2")).getText().then(function(the_elem_text) {
assert.equal("Second Span", the_elem_text);
});3. Verify the Page Text Contains a Piece of Text
A Page text is what we see on the web page, i.e., rendered text, without HTML tags.
Because WebDriver does not have driver.text method, we can achieve that with driver.find_element(:tag_name => "body").text.
matching_str = "Text assertion with a (tab before), and \n(new line before)!"
expect(driver.find_element(:tag_name => "body").text).to include(matching_str)Note: Keen readers will notice that the
matching_strin the above example is different to the one in scenario #1: it’s missing the HTML tags to bold the word “tab”. That’s because this element is just plain text and doesn’t include any styling.
4. Assert an element’s style.
To get the style of an element, look at the specific css_value and it’s attribute.
elem = driver.find_element(:id, "highlighted")
expect(elem.css_value("font-size")).to eq("15px")
expect(elem.css_value("background-color")).to eq("rgba(206, 218, 227, 1)")5. Assert the text in a table cell.
This is the same as scenario #2, simply use a locator on the table cell. In the below example, I used the XPath to get the second row’s second column’s cell text in cell_text.
cell_text = driver.find_element(:xpath, "//table/tbody/tr[2]/td[2]").text
expect(cell_text).to eq("b")Related reading:


