Rails 使用 minitest 和 fixture 进行模型测试

Rails Model test with minitest and fixture

我有一个小测验:

class CompanyTest < ActiveSupport::TestCase
  def setup
    @company = companies(:default)
  end

  test 'permalink should present' do
    @company.permalink = "     "
    assert_not @company.valid?
  end
end

默认公司的夹具是:

default:
  name: 'default'
  website: 'www.example.com'
  permalink: 'default'

我对公司模型进行了验证,如(company.rb):

validates :permalink, presence: true,  uniqueness: true
  before_validation :add_permalink

private
  def add_permalink
    self.permalink = self.name.to_s.parameterize
  end

令人惊讶的是,测试失败了。

  test_0001_permalink should present                              FAIL (95.55s)
Minitest::Assertion:         Expected true to be nil or false
        test/models/company_test.rb:31:in `block in <class:CompanyTest>'

我在内部 rails 中放置了一个 binding.pry 活动模型验证器:ActiveModel::Validations::PresenceValidator

class PresenceValidator < EachValidator # :nodoc:
      def validate_each(record, attr_name, value)
        binding.pry
        record.errors.add(attr_name, :blank, options) if value.blank?
      end
    end

这里的记录仍然有固定链接 default

[1] pry(#<ActiveRecord::Validations::PresenceValidator>)> record
=> #<Company:0x007f9ca5375070
 id: 593363170,
 name: "default",
 created_at: Wed, 15 Apr 2015 17:59:56 UTC +00:00,
 updated_at: Wed, 15 Apr 2015 17:59:56 UTC +00:00,
 website: "www.example.com",
 permalink: "default"

谁能帮我理解为什么测试失败以及为什么 ActiveModel::Validations::PresenceValidator 中的记录仍然与夹具数据完全匹配?

更新: 这是因为 before_validate,它基本上根据 name.

设置永久链接

您添加了一个 before_validation,当您调用 valid? 方法时,它会触发 before_validation 挂钩,因为您将其设置为公司名称,在本例中为公司名称是 default 以便您在控制台中将其作为 'default'.

您在 before_validation 挂钩中明确设置永久链接并测试它是否存在无效情况,这是不可能的。