Home > Software engineering >  Rails minitest, why is my article model invalid?
Rails minitest, why is my article model invalid?

Time:10-02

I am starting to get into testing with minitest in Rails. Currently my first test to see if my model is valid is returning false. The error message itself is also very generic Expected false to be truthy. I have tested everything else and all of those tests work fine. Does anybody know what could be causing this?

article_test.rb

require 'test_helper'

class ArticleTest < ActiveSupport::TestCase

    def setup
      @article = Article.new(title:"Avengers Endgame", body:"I am inevitable")
    end

    test "article should be valid" do
      assert @article.valid?
    end


    test "title should be present" do
        @article.title = " "
        assert_not @article.valid?
    end



    test "body should not be too short" do
        @article.body = "aa"
        assert_not @article.valid?
    end
end

article.rb

class Article < ApplicationRecord
    include Visible
    
    belongs_to :user
    has_many :comments, dependent: :destroy
    has_rich_text :body
    validates :title, presence: true
    validates :body, presence: true, length: { minimum: 10 }
  end

CodePudding user response:

The main problem here is that you're using a poor method for testing your validations.

assert @article.valid? and assert_not @article.valid? does not actually tell you anything at all about the object under test. When the test fails you're none the wiser about why it actually failed and if the failure is actually even connected to what you're proportedly testing. At best it serves as a sort of litmus test that your test setup is correct.

Instead of this "carpet bombing" approach test each validation on its own:

class ArticleTest < ActiveSupport::TestCas
  test "title should be present" do
    article = Article.new(title: '')
    article.valid?
    assert_includes build_article.errors[:title], "can’t be blank" 
  end

  test "body should not be too short" do
    article = Article.new(body: 'aa')
    article.valid?
    assert_includes article.errors[:body], "is too short" 
  end
end

Testing all the validations at once (creating a record with valid input) will be covered by your integration and system tests anyways.

CodePudding user response:

You have belongs_to :user, which expects the @article to have a user_id compulsorily to be present, before it can be saved.

If user_id is optional during creation, change this:

belongs_to :user

to

belongs_to :user, optional: true
  • Related