Appearance
Assertions ☑️
Assertions allow you to check the existence of a specific element or condition, and fail the test if the condition is not fulfilled.
To use an assertion, call should
or should_not
, and then chain the assertion.
users
.should.have(:table_row, ['Jane', 'Doe']
.should_not.have(:table_row, ['John', 'Doe'])
You can check the API Reference for information.
Custom Assertions 🎩
The example above becomes nicer to read if we define a more semantic version:
class UsersTestHelper < BaseTestHelper
def have_user(*names)
have(:table_row, names)
end
end
users
.should.have_user('Jane', 'Doe')
.should_not.have_user('John', 'Doe')
Notice that both the positive and negative assertions are available.
This is because built-in assertions like have
already handle the assertion state.
Understanding the Assertion State
When calling should
, any assertion calls that follow will execute the positive expectation.
users.should.have_selector('.user')
# same as
expect(users).to have_selector('.user')
On the other hand, after calling should_not
any assertions will execute the negated expectation.
users.should_not.have_selector('.user')
# same as
expect(users).not_to have_selector('.user')
Using the Assertion State
Sometimes built-in assertions are not enough, and you need to create your own expectation.
The assertion state is exposed as not_to
as syntax sugar.
Use to_or not_to
to create an expectation that can be used with should
or should_not
.
class CurrentPageTestHelper < BaseTestHelper
def fullscreen?
evaluate_script('Boolean(document.fullscreenElement)')
end
def be_fullscreen
expect(fullscreen?).to_or not_to, eq(true)
end
end
current_page.should.be_fullscreen
current_page.should_not.be_fullscreen
TIP
When creating your own assertions, it's important to ensure they are correctly synchronized.