GAURAV VARMA
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.
1assert_changes -> { user.address } do
2 user.update address: 'Miami'
3endassert_changes also supports from and to options.
1assert_changes -> { user.address }, from: 'San Francisco', to: 'Miami' do
2 user.update address: 'Miami'
3endSimilarly, assert_no_changes allows us to assert a value that is expected to
not change.
1assert_no_changes -> { user.address } do
2 user.update address: 'Miami'
3endWe can also specify an error message with assert_no_changes.
1assert_no_changes -> { user.address }, 'Expect the address to not change' do
2 user.update address: 'Miami'
3endBefore
assert_no_changes did not support the from option similar to
assert_changes.
1assert_no_changes -> { user.address } do
2 user.update address: 'Miami'
3endHowever, 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.
Rails 7 onwards
Provides the optional from argument to specify the expected initial value.
1assert_no_changes -> { user.address }, from: 'San Francisco' do
2 user.update address: 'Miami'
3endCheck out this pull request for more details.
This article was originally published on this website.