gpt4 book ai didi

ruby-on-rails - 使用 MiniTest 测试用户模型(设计身份验证)

转载 作者:行者123 更新时间:2023-12-05 02:22:25 25 4
gpt4 key购买 nike

我正在尝试测试用户模型,为此我设计了身份验证。

我面临的问题是,1. fixture 中有“password”/“password_confirmation”字段会给我无效列“password”/“password_confirmation”错误。

  1. 如果我从 fixture 中删除这些列并添加到 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

我想知道为什么我的用户对象无效?

谢谢

最佳答案

经过如下调查后,我得到了解决方法:为夹具添加辅助方法:

# 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'

并在用户测试中将此夹具用作用户对象。

def setup
@user = users(:default)
end

关于ruby-on-rails - 使用 MiniTest 测试用户模型(设计身份验证),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29388578/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com