まず、fixtures
は:all
/:context
/:suite hook
には使用できません。 (post(:my_post)
のような)これらのフックに器具を使用しないでください。
説明書/文脈ブロックでのみ備品を準備することができます。
コール
fixtures :students, :teachers
はDBに任意のデータをロードしないでください!単にヘルパーメソッドstudents
とteachers
を準備します。 最初にアクセスしようとすると、要求されたレコードが遅延してロードされます。直前
dan=students(:dan)
これはdelete all from table + insert fixtures
の方法で学生と教師を読み込みます。
あなたが前(:文脈)のフックでいくつかの学生を準備すれば、彼らは今すぐに行くでしょう!
レコードの挿入は、テストスイートで1回だけ実行されます。
テストスイートの最後には、フィクスチャからのレコードは削除されません。それらは削除され、次のテストスイートの実行時に再挿入されます。
例:これらの試験は、(次のスイート)をこの順に再度実行された場合のテストのすべての期待が上記予想より、
を通過する
#students.yml
dan:
name: Dan
paul:
name: Paul
#teachers.yml
snape:
name: Severus
describe Student do
fixtures :students, :teachers
before(:context) do
@james=Student.create!(name: "James")
end
it "have name" do
expect(Student.find(@james.id).to be_present
expect(Student.count).to eq 1
expect(Teacher.count).to eq 0
students(:dan)
expect(Student.find_by_name(@james.name).to be_blank
expect(Student.count).to eq 2
expect(Teacher.count).to eq 1
end
end
#but when fixtures are in DB (after first call), all works as expected (by me)
describe Teacher do
fixtures :teachers #was loade in previous tests
before(:context) do
@james=Student.create!(name: "James")
@thomas=Teacher.create!(name: "Thomas")
end
it "have name" do
expect(Teacher.find(@thomas.id).to be_present
expect(Student.count).to eq 3 # :dan, :paul, @james
expect(Teacher.count).to eq 2 # :snape, @thomas
students(:dan)
expect(Teacher.find_by_name(@thomas.name).to be_present
expect(Student.count).to eq 3
expect(Teacher.count).to eq 2
end
end
expect(Student.count).to eq 1
は満たされません! 3人の学生がいます(:dan、:paul、新鮮な新しい@james)。それらはすべてstudents(:dan)
の前に削除されます:paulと:danは再び挿入されます。
フィクスチャの代わりに[factory_girl](http://www.fabricationgem.org/)または[fabrication](http://www.fabricationgem.org/)に試してみてください。 –