我有一个模型'政策'。在该模型中,我对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.
当我认为应该通过时,最后一次测试是失败的。这让我觉得我的其他测试也不正确。
有一种更容易的方法来测试验证,而不涉及“地毯式轰炸”:
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?
不会告诉您有关错误消息中失败的内容。
在Rails 5中添加了errors.details
。在旧版本中,您需要使用:
assert_includes( policy.errors[:premium_amount], "can't be blank" )
哪个测试针对实际的错误消息。或者您可以使用active_model-errors_details向后移植该功能。
所以这里发生的是验证在模型上失败了。
如果在运行验证时对象没有错误,.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?
。