使用Minitest测试自定义验证器 [英] Testing custom validators with Minitest

查看:118
本文介绍了使用Minitest测试自定义验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个具有电子邮件验证功能的模型.因此,我已将验证提取到自定义验证器中.我是按照 Rails指南的教程来解决这个问题的.

I have multiple models with email validation. Therefore I've extracted the validation into a custom validator. I dit this by following the tutorial of the Rails Guides.

class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
      record.errors[attribute] << (options[:message] || "is not an email")
    end
  end
end

到目前为止,太好了.但是,由于我已经将电子邮件验证的功能提取到了自己的作用域中,因此我也想单独对其进行测试.我不想为每个模型添加相同的电子邮件格式测试.

So far, so good. But since I've extracted the functionality of email validation into it's own scope I also want to test it separately. I don't want to add the same email format tests to every model.

我找到了另一个问题,该问题也同样适用,但要求使用RSpec.但是由于我还没有使用存根和模拟,所以我不知道如何将测试移植到Minitest测试中.我没有找到任何资源可以用Minitest测试自定义验证器.

I found another question which also asked the same but for RSpec. But since I haven't worked with stubs and mocks yet, I don't know how to port the tests to Minitest tests. I haven't found any resources which test custom validators with Minitest.

有人知道如何在Minitest中为自定义验证器编写此类测试(不使用规范!)?

Does anybody know how to write such tests for custom validators in Minitest (not using specs!)?

推荐答案

您要问的是(我认为)正在隔离中测试此验证器.这意味着它将在隔离测试中进行一次测试,该测试将完全按照您说的做:

What (I think) you are asking for here is testing this validator in isolation. This means that it will be tested once, in an isolated test, which will do exactly what you said:

我不想为每个模型添加相同的电子邮件格式测试.

I don't want to add the same email format tests to every model.

我在这里采用的方法是在测试文件中仅创建一个测试类,并混入ActiveRecord::Validations模块并测试该类本身.

The approach I would take here is to create just a test class in a test file, mix-in the ActiveRecord::Validations module and test the class itself.

# test_file.rb
require 'test_helper'

class EmailValidatable
  include ActiveModel::Validations
  validates_with EmailValidator
  attr_accessor  :email
end

class EmailValidatorTest < Minitest::Test
  def test_invalidates_object_for_invalid_email
    obj = EmailValidatable.new
    obj.email = "invalidemail"
    refute obj.valid?
  end

  def test_adds_error_for_invalid_email
    obj = EmailValidatable.new
    obj.email = "invalidemail"
    refute_nil obj.errors[:email]
  end

  def test_adds_no_errors_for_valid_email
    obj = EmailValidatable.new
    obj.email = "valid@email.com"
    assert_nil obj.errors[:email]
    assert obj.valid?
  end
end

我还没有测试上面的代码,但是我认为它应该给您一个想法/方向.

I haven't tested the code above, but I think that it should give you an idea/direction.

HTH

这篇关于使用Minitest测试自定义验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆