Testing User Model (Devise Authentication) with MiniTest

 ̄綄美尐妖づ 提交于 2019-12-21 22:38:38

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/29388578/testing-user-model-devise-authentication-with-minitest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!