Rails 7: Add from: option to ActiveSupport::TestCase#assert_no_changes
source link: https://blog.saeloun.com/2021/10/26/rails-7-add-from-to-assert_no_changes
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
ActiveSupport has a ton of great assertions that make writing tests a joy!
One such welcome change is the addition of the from
option to assert_no_changes
.
Let’s have a look at what changed.
Before
To test if an action changes the value of an object, there is a useful assertion that ActiveSupport provides.
assert_changes -> {blog.title} do
blog.update title: "new title"
end
This assertion has support for from
and to
parameters as well, making it easier to monitor changes.
assert_changes -> {blog.title}, from: 'original title', to: 'new title' do
blog.update title: "new title"
end
It is also possible to monitor if the object does not change, using the following assertion,
assert_no_changes -> {blog.category} do
blog.update title: "new title"
end
However, we were not provided with a from
option for this assertion.
Hence, asserting that no change occurs from a fixed starting point was not easy to determine.
After
Thanks to this PR, we now have a from
option.
It makes it easy to assert that no change occurred during a transaction.
assert_no_changes -> {blog.category}, from: blog.category do
blog.update title: "new title"
end
It permits asserting on the initial value that is expected not to change.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK