我想运行一些RSpec测试来测试Rails中的Ancestry。我想使用FactoryGirl为测试创建Institution实例。我尝试了下面提到的以下方法,但是没有成功创建子记录。
factories.rb文件
factory :institution do
# sequence(:name) { |n| "University of XYZ#{n}" }
end
在测试中我使用以下样式 风格:1
let(:institution){ FactoryGirl.create(:institution, name: "ABC Institution") }
let(:institution_child) {FactoryGirl.create(:institution, name: "Sub Institution", ancestry: institution.id) }
风格:2
let(:institution){ FactoryGirl.create(:institution, name: "ABC Institution") }
let(:institution_child) {FactoryGirl.create(:institution, name: "Sub Institution", parent_id: institution.id) }
风格: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
我已经使用RSpec搜索了Rails Ancestry测试的例子,但没有找到任何非常有用的东西。如果任何人有任何他们可以指出的工作解决方案或来源,那将非常有帮助。提前致谢。
答案 0 :(得分:4)
factory :institution do
sequence(:name) { |n| "ABC Institution" }
factory :institution_child do |f|
# f.sequence(:name) { |n| "Here you can override name for child" }
f.parent FactoryGirl.create(:institution)
end
end
现在在规格中,您可以调用:institution_child
factory,以使用parent:
describe Institution do
let!(:institution_child) {FactoryGirl.create(:institution_child, name: "Sub Institution") }
it "should create the child institution" do
assigns(:institution_child).should eq institution_child
assigns(:institution_child).parent.should eq institution_child.parent
# just for test
institution_child.parent.should_not be_nil
end
end
factory :institution do
sequence(:name) { |n| "ABC Institution" }
trait :with_parent do
after(:build) do |o|
o.parent = FactoryGirl.create(:institution)
end
end
end
现在在规格中你可以这样使用它:
describe Institution do
let(:institution_child) {FactoryGirl.create(:institution_child,:with_parent, name: "Sub Institution") }
#...
end