不要让`should validate_inclusion_of`在Rails3.2,RSpec2中工作

时间:2012-06-26 11:19:36

标签: ruby-on-rails ruby rspec

型号:

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"]

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

3 个答案:

答案 0 :(得分: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 do | gender |     它{should_not validate_inclusion_of(:gender).in(性别)}   端

答案 1 :(得分: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

答案 2 :(得分: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
  #