I want to run some RSpec tests to test Ancestry in Rails. I want to use FactoryGirl to create the Institution instances for the tests. I have tried the following ways mentioned below, but have not been successful in creating the child records.
factories.rb file
factory :institution do
# sequence(:name) { |n| "University of XYZ#{n}" }
end
And in the tests I am using the following styles Style: 1
let(:institution){ FactoryGirl.create(:institution, name: "ABC Institution") }
let(:institution_child) {FactoryGirl.create(:institution, name: "Sub Institution", ancestry: institution.id) }
Style: 2
let(:institution){ FactoryGirl.create(:institution, name: "ABC Institution") }
let(:institution_child) {FactoryGirl.create(:institution, name: "Sub Institution", parent_id: institution.id) }
Style: 3
describe Institution do
before do
@institution = Institution.create({:institution, name: "ABC Institution"})
@institution_child = Institution.create(:institution, name: "Sub Institution"}
end
it "should create the child institution" do
assigns(:institution_child).should be_a_new(Institution)
assigns(:institution_child).parent_id.should eq @institution.id
end
end
I have searched for examples of Rails Ancestry testing using RSpec but haven't found anything quite useful. If anyone has any working solution or sources that they could point me to, it will be very helpful. Thanks in advance.
Option 1, using nested factories:
Now in specs, you can just call
:institution_child
factory, too create it with parent:Option 2, using traits:
Now in specs you can use it like that: