使用MiniTest测试用户模型(Devise身份验证)
我正在尝试测试用户模型,为此我设计了身份验证.
I'm trying to test user model, for which I've devise authentication.
我面临的问题是, 1.固定装置中有'password'/'password_confirmation'字段会给我无效的列'password'/'password_confirmation'错误.
The problem I'm facing is, 1. Having 'password'/'password_confirmation' fields in fixtures is giving me invalid column 'password'/'password_confirmation' error.
-
如果我从灯具中删除这些列并添加到user_test.rb
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
我得到的错误是:
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?
谢谢
经过如下调查,我得到了解决: 为灯具添加辅助方法:
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
并像这样制作夹具:
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