[英]Rails Minitest custom model validation test doesn't create an object
我有一个User
model 进行验证,当新用户的 account_type 设置为'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
块没有运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.