MiniTest模型测试失败

时间:2019-04-24 19:39:32

标签: 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

这是我的控制人:

class PoliciesController < ApplicationController
  def create
    policy = Policy.create!(policy_params)
    render json: policy
  end

  private
    def policy_params
      params.require(:policy).permit(:policy_holder, :premium_amount, :industry_id,
                                     :carrier_id, :agent_id)
    end
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.

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

2 个答案:

答案 0 :(得分:1)

有一种更简单的方法来测试验证,从而减少涉及的“地毯炸弹”:

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来向后移植功能。

答案 1 :(得分:0)

所以这里发生的是模型验证失败。

如果运行验证时对象上没有错误,则

.valid?将返回true

由于您清楚地看到“假”,这意味着模型上的一个或多个验证失败。

在Rails控制台中,您应该尝试手动创建一个对象并将其强制转换为变量,然后对其进行测试以查看错误,从而:

test = Policy.new(whatever params are needed to initialize here)
# This will give you the object

test.valid?
#This will likely return FALSE, and NOW you can run:

test.errors
#This will actually show you where the validation failed inside the object

无论如何,这几乎肯定是模型及其创建中的问题。

请记住,在对对象运行.errors之后,.valid?才起作用。