3

下面是我正在使用的代码:

这是我的app/models文件:

class One < ActiveRecord::Base
  attr_accessible :name, :surname      
end

class Two < ActiveRecord::Base  
  attr_accessible :name, :one_surname

  # generate a list of one's surnames
  def self.LIST_SURNAMES
    list  = Array.new
    arr   = One.all
    arr.each {|one| list << one.surname}

    return list
  end

  validates :one_surname, :inclusion => self.LIST_SURNAMES()
end

这是我的/spec/models文件:

FactoryGirl.define do
  factory :two do
    name "two_name"
  end

  factory :one do
    name "one_name"
    surname "one_surname"
  end    
end

describe Two do
  it 'should be created' do
    @one = FactoryGirl.create(:one)

    puts "One.last.surname = #{One.last.surname}"
    puts "Two.LIST_SURNAMES = #{Two.LIST_SURNAMES}"

    @two = FactoryGirl.build(:two, :one_surname => Two.LIST_SURNAMES[0])

    @two.save!
  end
end 

但是,我的测试失败了。我完全不确定这是为什么。有什么想法吗?

这是RSpec输出:

One.last.surname  = one_surname
Two.LIST_SURNAMES = ["one_surname"]

此外,我遇到了这个失败:

  1) Two should be created
     Failure/Error: @two.save!
     ActiveRecord::RecordInvalid:
       Validation failed: One surname is not included in the list
 # ./category_spec.rb:29:in `block (2 levels) in <top (required)>'
4

1 回答 1

5

它在解释时执行 Two.LIST_SURNAMES,而不是运行时。因此,如果您希望它在运行时获取 LIST_SURNAMES,则需要使用 proc

validates :one_surname, :inclusion => {:in => proc {self.LIST_SURNAMES()}}

其余的是可选的,但这里有一些干净的代码:

class Two < ActiveRecord::Base
  attr_accessible :name, :one_surname

  validates :one_surname, :inclusion => {in: proc{One.pluck(:surname)}}                                              
end

我替换了做同样事情的LIST_SURNAMES方法。One.pluck(:surname)另外:LIST_SURNAMES,如果你保留它,应该是def self.list_surnames因为它不是一个常数。

于 2012-06-06T16:08:08.793 回答