不要让"应该validate_inclusion_of"在 Rails3.2、RSpec2 中工作



Model:

class Contact < ActiveRecord::Base
  validates :gender, :inclusion => { :in => ['male', 'female'] }
end

迁移:

class CreateContacts < ActiveRecord::Migration
  def change
    create_table "contacts", :force => true do |t|
      t.string  "gender",  :limit => 6, :default => 'male'
    end
  end
end

RSpec 测试:

describe Contact do
  it { should validate_inclusion_of(:gender).in(['male', 'female']) }
end

结果:

Expected Contact to be valid when gender is set to ["male", "female"]

有人知道为什么这个规范没有通过吗?或者任何人都可以重建和(验证)它吗?谢谢。

我误解了如何使用.in(..)。我以为我可以传递一个值数组,但似乎它只接受一个值:

describe Contact do
  ['male', 'female'].each do |gender|
    it { should validate_inclusion_of(:gender).in(gender) }
  end
end

我真的不知道使用allow_value有什么区别:

['male', 'female'].each do |gender|
  it { should allow_value(gender).for(:gender) }
end

我想检查一些不允许的值总是一个好主意:

[:否, :有效, :性别]。每个都做 |性别| it { should_not validate_inclusion_of(:gender).in(gender) } 结束

我通常更喜欢直接测试这些东西。例:

%w!male female!.each do |gender|
  it "should validate inclusion of #{gender}" do
    model = Model.new(:gender => gender)
    model.save
    model.errors[:gender].should be_blank
  end
end
%w!foo bar!.each do |gender|
  it "should validate inclusion of #{gender}" do
    model = Model.new(:gender => gender)
    model.save
    model.errors[:gender].should_not be_blank
  end
end
你需要

使用in_array

从文档中:

  # The `validate_inclusion_of` matcher tests usage of the
  # `validates_inclusion_of` validation, asserting that an attribute can
  # take a whitelist of values and cannot take values outside of this list.
  #
  # If your whitelist is an array of values, use `in_array`:
  #
  #     class Issue
  #       include ActiveModel::Model
  #       attr_accessor :state
  #
  #       validates_inclusion_of :state, in: %w(open resolved unresolved)
  #     end
  #
  #     # RSpec
  #     describe Issue do
  #       it do
  #         should validate_inclusion_of(:state).
  #           in_array(%w(open resolved unresolved))
  #       end
  #     end
  #
  #     # Test::Unit
  #     class IssueTest < ActiveSupport::TestCase
  #       should validate_inclusion_of(:state).
  #         in_array(%w(open resolved unresolved))
  #     end
  #
  # If your whitelist is a range of values, use `in_range`:
  #
  #     class Issue
  #       include ActiveModel::Model
  #       attr_accessor :priority
  #
  #       validates_inclusion_of :priority, in: 1..5
  #     end
  #
  #     # RSpec
  #     describe Issue do
  #       it { should validate_inclusion_of(:state).in_range(1..5) }
  #     end
  #
  #     # Test::Unit
  #     class IssueTest < ActiveSupport::TestCase
  #       should validate_inclusion_of(:state).in_range(1..5)
  #     end
  #

最新更新