Undefined method: assert_not_nil in Minitest
Asked Answered
P

4

6

I'm trying to execute the following code, but it is giving me an undefined method error:

require 'minitest/autorun'
require 'string_extension'

class StringExtensionTest < Minitest::Test
  def test_humanize_returns_nothing
    assert_not_nil "Yo".humanize, "humanize is returning nil."
  end
end

I'm trying to execute this code from Codeschool's Rails course, but it seems that there is no method assert_not_nil. I've also checked the documentation for MiniTest framework, and neither it is defined there, but I'm not sure.

Pliske answered 12/3, 2016 at 9:48 Comment(0)
W
6

Here you can find the list of assertions defined by MiniTest.

As you can see, assert_not_nil is not defined. There's a lot of possible assertions that MiniTest doesn't define, but it's also true that any assertion can be defined with the simplest assertion ever possible assert.

In your specific case:

assert result != nil

You can also pass a custom message

assert result != nil, "Expected something to not be nil"
Wilek answered 12/3, 2016 at 10:14 Comment(1)
Well that was the information I needed to know if I should change to MiniTest::Test or stick with Test::Unit::TestCase. Basic assert doesn't produce readable error message so Test::Unit::TestCase it is.Chimerical
B
6

assert_not_nil is just an alias for refute_nil, but it's Rails-only, not part of standard Minitest. Changing your test to extend ActiveSupport::TestCase should do the trick:

class StringExtensionTest < ActiveSupport::TestCase
  def test_humanize_returns_nothing
    assert_not_nil "Yo".humanize, "humanize is returning nil."
  end
end
Blueness answered 12/3, 2016 at 10:15 Comment(0)
H
0

assert !!result has worked for me. !! means "convert to boolean" (literally double negation).

Homemade answered 19/8, 2020 at 21:42 Comment(0)
U
-1

You can use

assert "Yo".humanize

In ruby everthing but nil and false is true-ish.

UPDATE: since you want to check explicetly for not nil:

refute_nil "Yo".humanize

But in the scenario you describe i'd actually check for the return value to be what I expect. Consider:

class String
  def humanize
    false
  end
end

refute_nil "Yo".humanize
assert_equal "Yo", "Yo".humanize
Unduly answered 12/3, 2016 at 10:5 Comment(2)
Well, it will check that it does return something, while I'd like to check it the other way.Pliske
"assert <anything>" doesn't work when <anything> is nil - I'm surprised, frankly. I have to do assert !!<anything> to make it work.Homemade

© 2022 - 2024 — McMap. All rights reserved.