I'm having trouble with an RSpec test, and I suspect it may be to do with my explicit use of subject in the before block. Notably, I am testing ActiveRecord objects that have a has_many / belongs_to relationship. This is my failing test:
subject { FactoryGirl.create(:parent) }
let(:child) { FactoryGirl.build(:child) }
context "with added child object" do
before { subject.children << child }
its(:foo) { is.expected_to eq("bar")
end
In my parent model I have some simple logic based on adding the child record which works outside of the test. Since it doesn't work in the test, I switched to writing the spec part out long-form to try and understand why:
before do
puts "subject is #{subject}"
puts "child is #{child}"
subject.children << child
puts "#{child_to_attach} is now attached to #{child_to_attach.parent}"
end
it "has the correct response" do
puts "testing against subject #{subject}"
expect(subject.foo).to eq("bar")
end
And the output I got suggests that something weird is happening - that the subject I attach the child to is a different one than the rest of the test:
subject is #<Parent:0x00561eddf1a7a0>
child is #<Child:0x00561edcdd7fb0>
#<Child:0x00561edcdd7fb0> is now attached to #<Parent:0x00561edd11c040>
testing against subject #<Parent:0x00561eddf1a7a0>
Am I doing something wrong with subject to cause this behaviour? Is there a better way to write this test?
Aucun commentaire:
Enregistrer un commentaire