Below is the code that I am using:
This is my app/models file:
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
This is my /spec/models file:
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
However, my test fails. And I'm entirely unsure of why this is. Any thoughts?
This is the RSpec output:
One.last.surname = one_surname
Two.LIST_SURNAMES = ["one_surname"]
Further, I am getting this failure:
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)>'
It's executing the Two.LIST_SURNAMES at interpretation time, not runtime. So if you want it to get the LIST_SURNAMES at runtime, you'll need to use a proc
validates :one_surname, :inclusion => {:in => proc {self.LIST_SURNAMES()}}
The rest is optional, but here's some cleaned code:
class Two < ActiveRecord::Base
attr_accessible :name, :one_surname
validates :one_surname, :inclusion => {in: proc{One.pluck(:surname)}}
end
I replaced the LIST_SURNAMES method with One.pluck(:surname) which does the same thing. Also: LIST_SURNAMES, if you keep it, should be def self.list_surnames since it is not a constant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With