简体   繁体   English

Rails-FactoryGirl-测试模型[验证]

[英]Rails - FactoryGirl - test models [validation]

I would like to test my models but all informations that I could find seems to be outdated. 我想测试我的模型,但是我能找到的所有信息似乎都已过时。 My goal is to test each individual validation. 我的目标是测试每个单独的验证。 My model: 我的模特:

class Author < ActiveRecord::Base
  has_and_belongs_to_many :books
  before_save :capitalize_names
  validates :name, :surname, presence: true, length: { minimum: 3 },
  format: { with: /[a-zA-Z]/ }


  private
  def capitalize_names
    self.name.capitalize!
    self.surname.capitalize!
  end
end

and my factorygirl define: 和我的factorygirl定义:

FactoryGirl.define do
  factory :author do |f|
    f.name { Faker::Name.first_name }
    f.surname { Faker::Name.last_name }
  end
end

So now, I want to test whether name is not shorter than 3 characters. 所以现在,我要测试名称是否不少于3个字符。

My context: 我的情况:

  context 'when first name is too short' do
    it { expect( FactoryGirl.build(:author, name: 'Le')).to 
      be_falsey }
    end

I know it's invalid because of [FactoryGirl.build(:author, name: 'Le')] returns hash instead of boolean value. 我知道它是无效的,因为[FactoryGirl.build(:author,name:'Le')]返回哈希值而不是布尔值。 So now, how should I test it? 那么现在,我应该如何测试呢? What matcher should I use? 我应该使用什么匹配器?

[SOLVED] [解决了]

Use be_valid instead of be_falsey. 使用be_valid而不是be_falsey。 Now it should look like : 现在应该看起来像:

 context 'when first name is too short' do
    it { expect( FactoryGirl.build(:author, name: 'Le')).not_to
    be_valid }
  end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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