问题描述
当新用户将 account_type 设置为 User
时,我有一个带有验证的 'organisation'
模型,company_name
应该是强制性的。
class User < ApplicationRecord
ACCOUNT_TYPES = %w[individual organisation].freeze
validates :company_name,presence: true,if: :organisation_account?
private
def organisation_account?
account_type == ACCOUNT_TYPES[1]
end
end
我想使用 Minitest 和 Shoulda Matchers 测试此验证,如下所示:
require 'test_helper'
class UserTest < ActiveSupport::TestCase
setup do
@user = users(:active)
end
context 'validations' do
context 'when account_type is organisation' do
@user.account_type = 'organisation'
should validate_presence_of(:company_name)
end
end
但是测试显示了一个错误:undefined method account_type=' for nil:NilClass (NoMethodError)
这意味着由于某种原因 setup
块没有创建用户。我错过了什么?
解决方法
我错过了什么?
您的测试应该在 it
块中。 context
块只是设置测试环境,它们不定义测试。
而且,由于此文件中没有单个测试,因此 setup
块没有运行。