Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: "[email protected]",
                             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

like image 509
Indyarocks Avatar asked Apr 20 '26 16:04

Indyarocks


1 Answers

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: '[email protected]'
  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
like image 141
Indyarocks Avatar answered Apr 22 '26 04:04

Indyarocks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!