November 19, 2021
This blog is part of our Rails 7 series.
Rails Active Support provides various extensions, utilities, and helpers. It provides a collection of utility classes and standard library extensions that are very useful.
Rails 5.1 introduced assert_no_changes
and assert_changes
making it easier
to observe changes. Using
ActiveSupport::TestCase#assert_no_changes
we can easily assert that the result of evaluating an expression has not changed
before and after calling the passed block.
To assert the expected change in the value of an object we can use
assert_changes
.
assert_changes -> { user.address } do
user.update address: 'Miami'
end
assert_changes
also supports from
and to
options.
assert_changes -> { user.address }, from: 'San Francisco', to: 'Miami' do
user.update address: 'Miami'
end
Similarly, assert_no_changes
allows us to assert a value that is expected to
not change.
assert_no_changes -> { user.address } do
user.update address: 'Miami'
end
We can also specify an error message with assert_no_changes
.
assert_no_changes -> { user.address }, 'Expect the address to not change' do
user.update address: 'Miami'
end
assert_no_changes
did not support the from
option similar to
assert_changes
.
assert_no_changes -> { user.address } do
user.update address: 'Miami'
end
However, Rails 7 has added from: option to ActiveSupport::TestCase#assert_no_changes, allowing us to assert on the initial value that is expected to not change.
Provides the optional from
argument to specify the expected initial value.
assert_no_changes -> { user.address }, from: 'San Francisco' do
user.update address: 'Miami'
end
Check out this pull request for more details.
If this blog was helpful, check out our full blog archive.