Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 [email protected]?
end
like image 403
Gabrijel Šimunović Avatar asked Jan 15 '15 20:01

Gabrijel Šimunović


1 Answers

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 [email protected]?
  # 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.

like image 75
Nick Veys Avatar answered Sep 28 '22 08:09

Nick Veys