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

标签 ruby-on-rails testing minitest

我有一个模型“政策”。在该模型中,我对 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/

相关文章:

ruby-on-rails - 将对象放入 aws S3 ruby​​ 中的特定文件夹

testing - 如何使用Grails 3.2.4设置Cucumber以进行Grails测试?

javascript - 无法读取试图进行任何操作的源文件夹

ruby-on-rails - 在 Rails 4 中使用具有间隙的 fixture 进行单元测试用户模型

ruby-on-rails - Rails 没有正确加载 4 个 fixtures 文件之一

ruby - 使用 MiniTest 测试方法是否被调用 x 次的更好方法?

ruby-on-rails - 获取并发布相同匹配项的请求

ruby-on-rails - 参数错误 : SMTP-AUTH requested but missing user name + ActionMailer

mysql - 如何使用 Rails 解决 MySQL 锁定超时错误?

unit-testing - 引用错误 : ShadowRoot is not defined Jest and Vue3