Gabrijel Šimunović Gabrijel Šimunović - 5 months ago 13
Ruby Question

Why 'assert_not' and not '!' when writing Rails tests?

Consider this example, we'd like to check whether it's allowed for user to have blank name (it shouldn't be):

test "name should be present" do
@user.name = " "
assert_not @user.valid?
end


The question is why does
assert_not
exists? Wouldn't it be better if we just use
assert
like this:

test "name should be present" do
@user.name = " "
assert !@user.valid?
end

Answer

It likely exists to remove modifiers from your assertions, which may change their results or obscure what you're actually asking. In reality, it's mostly a style choice.

It's kind of the same motivation for having unless in the language, instead of writing this:

if !@user.valid?
  # do stuff
end

You would do:

unless @user.valid?
  # do stuff
end

Granted, the if/unless differences read way better than assert_not, alas that's what Minitest unit tests are going to get you. If you want things to read more naturally, take a look at Minitest specs or RSpec.

Comments