1

模型:

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)验证它吗?谢谢你。

4

3 回答 3

2

我误解了.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

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

[:no, :valid, :gender].each 都做 |gender| 它 { should_not validate_inclusion_of(:gender).in(gender) } end

于 2012-07-09T13:49:55.203 回答
1

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

%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
于 2012-06-26T15:32:25.557 回答
0

你需要使用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
  #
于 2015-05-27T18:29:33.990 回答