以下是我正在使用的代码:
这是我的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)>'
答案 0 :(得分: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
,因为它不是常数。