Mike
Mike

Reputation: 169

Testing if a method returns a `non-null` value

Im testing if my method populate() returns a non-null value (which it does, it returns an integer > 0) but having troubles to correctly write it. I have:

describe House::Room do
  describe '.populate' do
    let(:info) {
      $info = {"people"=>
                        {"name"=>"Jordan",
                         "last_name"=>"McClalister"}}
              }
    it 'should return an integer > 0' do
      expect(House::Room.populate(info)).not_to eq(nil)
    end
  end
end

Upvotes: 4

Views: 8353

Answers (2)

Mike Slinn
Mike Slinn

Reputation: 8403

rubocop-rspec favors be_nil over be(nil), according to RSpec/BeNil.

Thus, the answer provided by @GabrielBonner is better expressed as:

describe House::Room do
  describe '.populate' do
    let(:info) {"people"=>
                        {"name"=>"Jordan",
                         "last_name"=>"McClalister"}
               }
    it 'should return an integer > 0' do
      expect(House::Room.populate(info)).not_to be_nil
    end
  end
end

Upvotes: 0

Gabriel Bonner
Gabriel Bonner

Reputation: 89

You'll need to change the let assignment to:

describe House::Room do
  describe '.populate' do
    let(:info) {"people"=>
                        {"name"=>"Jordan",
                         "last_name"=>"McClalister"}
               }
    it 'should return an integer > 0' do
      expect(House::Room.populate(info)).not_to be(nil)
    end
  end
end

That should make your code work as you expect.

However, you could also use another matcher, like 'be_within' if you wanted to be more specific, or write several expect statements in the same test, like 'expect to be an integer', 'expect to be greater than 0', etc... There is no limit to the number of expect statements you can have in an 'it' block, the test will only pass if all of the expectations are fulfilled. (That said, I believe best practice would be to split it up into individual tests.)

Upvotes: 7

Related Questions