Search code examples
ruby-on-railsruby-on-rails-4devisetddminitest

Testing User Model (Devise Authentication) with MiniTest


I'm trying to test user model, for which I've devise authentication.

The problem I'm facing is, 1. Having 'password'/'password_confirmation' fields in fixtures is giving me invalid column 'password'/'password_confirmation' error.

  1. If I remove these columns from fixture and add in user_test.rb

    require 'test_helper'
    
    class UserTest < ActiveSupport::TestCase
    
    
          def setup
            @user = User.new(name: "example user",
                             email: "example@example.com",
                             password: "Test123",
                             work_number: '1234567890',
                             cell_number: '1234567890')
          end
    
          test "should be valid" do
            assert @user.valid?
          end
    
          test "name should be present" do
            @user.name = "Example Name "
            assert @user.valid?
          end
    
        end
    

The error I'm getting is:

  test_0001_should be valid                                       FAIL (0.74s)
Minitest::Assertion:         Failed assertion, no message given.
        test/models/user_test.rb:49:in `block in <class:UserTest>'

  test_0002_name should be present                                FAIL (0.01s)
Minitest::Assertion:         Failed assertion, no message given.
        test/models/user_test.rb:54:in `block in <class:UserTest>'


Fabulous run in 0.75901s
2 tests, 2 assertions, 2 failures, 0 errors, 0 skips

I'm wondering why my user object is not valid?

Thanks


Solution

  • I got a work around after some investigation like below: Add a helper method for fixture:

    # test/helpers/fixture_file_helpers.rb
    module FixtureFileHelpers
      def encrypted_password(password = 'password123')
        User.new.send(:password_digest, password)
      end
    end
    
    # test/test_helper.rb
    require './helpers/fixture_file_helpers.rb'
    ActiveRecord::FixtureSet.context_class.send :include, FixtureFileHelpers
    

    And make fixture like this:

    default:
      email: 'default@example.com'
      name: "User name"
      encrypted_password: <%= encrypted_password %>
      work_number: '(911) 235-9871'
      cell_number: '(911) 235-9871'
    

    And use this fixture as user object in user test.

    def setup
        @user = users(:default)
    end