MiniTest 模型验证测试失败

has*_*ket 3 testing ruby-on-rails minitest

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

这是我的模型:

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

  validates :policy_holder,  presence: true
  validates :premium_amount, presence: true
end
Run Code Online (Sandbox Code Playgroud)

这是我的测试:

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
Run Code Online (Sandbox Code Playgroud)

这是失败消息:

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.
Run Code Online (Sandbox Code Playgroud)

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

max*_*max 5

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

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
Run Code Online (Sandbox Code Playgroud)

这仅测试该验证,而不测试模型上的所有验证。使用assert policy.valid?不会告诉您错误消息中失败的任何内容。

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

assert_includes( policy.errors[:premium_amount], "can't be blank" )
Run Code Online (Sandbox Code Playgroud)

它针对实际的错误消息进行测试。或者您可以使用active_model-errors_details来向后移植该功能。