davidm
davidm

Reputation: 89

RoR: Minitest error: Expected false to be truthy

looking for help implementing a simple first test using minitest (Rails 5, Ruby 2.7.0)

car_test.rb

require 'test_helper'

class CarTest < ActiveSupport::TestCase

  test 'valid car' do
    car = Car.new(title: 'SALOON', style: '1')
    assert car.valid?
  end

end

My model car.rb

class Car < ApplicationRecord
    validates :title, :style, presence: true
end

When I run test: rake test TEST=test/models/car_test.rb

Expected false to be truthy.

I don't know what I am doing wrong? Thanks.

Upvotes: 0

Views: 880

Answers (1)

max
max

Reputation: 102368

assert thing.valid? is a testing anti-pattern that was popularized by the Rails Tutorial book. Its an anti-pattern since you're testing every single validation at once and the possibilities for both false positives and negatives are huge. The error message also tells you absolutely nothing about why the test failed.

Instead if you want to test validations use the errors object.

require 'test_helper'

class CarTest < ActiveSupport::TestCase
  test 'title must be present' do
    car = Car.new(title: '')
    car.valid?
    assert_includes car.errors.messages[:title], "can't be blank"
  end
  test 'style must be present' do
    car = Car.new(style: '')
    car.valid?
    assert_includes car.errors.messages[:style], "can't be blank"
  end
end

Upvotes: 1

Related Questions