繁体   English   中英

Rails Minitest 自定义 model 验证测试不会创建 object

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM