gpt4 book ai didi

ruby-on-rails - MiniTest 模型验证测试失败

转载 作者:行者123 更新时间:2023-11-28 20:26:14 25 4
gpt4 key购买 nike

我有一个模型“政策”。在该模型中,我对 policy_holder 和 premium_amount 进行了存在验证。我正在尝试为此模型编写一个 MiniTest 测试。由于某种原因,我的测试失败了。

这是我的模型:

class Policy < ApplicationRecord
belongs_to :industry
belongs_to :carrier
belongs_to :agent

validates :policy_holder, presence: true
validates :premium_amount, presence: true
end

这是我的测试:

require 'test_helper'

class PolicyTest < ActiveSupport::TestCase
test 'should validate policy holder is present' do
policy = Policy.find_or_create_by(policy_holder: nil, premium_amount: '123.45',
industry_id: 1, carrier_id: 1,
agent_id: 1)
assert_not policy.valid?
end

test 'should validate premium amount is present' do
policy = Policy.find_or_create_by(policy_holder: 'Bob Stevens', premium_amount: nil,
industry_id: 1, carrier_id: 1,
agent_id: 1)
assert_not policy.valid?
end

test 'should be valid when both policy holder and premium amount are present' do
policy = Policy.find_or_create_by(policy_holder: 'Bob Stevens', premium_amount: '123.45',
industry_id: 1, carrier_id: 1,
agent_id: 1)
assert policy.valid?
end
end

这是失败信息:

Failure:
PolicyTest#test_should_be_valid_when_both_policy_holder_and_premium_amount_are_present [test/models/policy_test.rb:22]:
Expected false to be truthy.

当我认为应该通过时,最后一个测试却失败了。这让我认为我的其他测试也不正确。

最佳答案

有一种更简单的方法来测试验证,并且涉及更少的“地毯式轰炸”:

require 'test_helper'

class PolicyTest < ActiveSupport::TestCase
setup do
@policy = Policy.new
end

test "should validate presence of policy holder" do
@policy.valid? # triggers the validations
assert_includes(
@policy.errors.details[:policy_holder],
{ error: :blank }
)
end

# ...
end

这仅测试该验证,而不是对模型的所有验证组合。使用 assert policy.valid? 不会在错误消息中告诉您任何有关失败的信息。

errors.details 是在 Rails 5 中添加的。在旧版本中,您需要使用:

assert_includes( policy.errors[:premium_amount], "can't be blank" )

根据实际错误消息进行测试。或者你可以使用 active_model-errors_details向后移植该功能。

关于ruby-on-rails - MiniTest 模型验证测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55837414/

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