为什么在此RSpec设置中测试了错误的对象?

时间:2016-11-01 14:03:22

标签: ruby-on-rails ruby testing activerecord rspec

我在使用RSpec测试时遇到问题,我怀疑这可能与我在前一块中明确使用主题有关。值得注意的是,我正在测试具有has_many / belongs_to关系的ActiveRecord对象。这是我的失败测试,​​我试图断言父母有一些基于添加孩子的事件的行为:

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

在我的父模型中,我有一些简单的逻辑,基于添加在测试之外工作的子记录。由于它在测试中不起作用,我转而编写长篇版本的规范部分以试图理解原因:

before do
  puts "subject is #{subject}"
  puts "child is #{child}"
  subject.children << child 
  puts "#{child} is now attached to #{child.parent}"
end

it "has the correct response" do
  puts "testing against subject #{subject}"
  expect(subject.foo).to eq("bar")
end

我得到的输出表明发生了一些奇怪的事情 - 我将孩子附加到的主题是与设置和测试块中的不同的主题

subject is #<Parent:0x00561eddf1a7a0>                                                  
child is #<Child:0x00561edcdd7fb0>
#<Child:0x00561edcdd7fb0> is now attached to #<Parent:0x00561edd11c040>
testing against subject #<Parent:0x00561eddf1a7a0>

我做错了导致这种行为吗?有没有更好的方法来编写这个测试?

根据以下建议更新

当我像这样构建测试时,它会通过,并且输出不包含任何神秘的第二版父母。

before do
  child = FactoryGirl.create(:child, parent: parent)      
end

it "has the correct response" do
  # some puts to check the states of the various models here
  expect(subject.foo).to eq("bar")
end

然而,这并不是客户使用该课程的方式 - 可以通过多种不同的方法添加孩子,我希望模型以相同的方式行事,无论如何

这也没有回答这个问题 - 第一次设置中的额外对象在哪里?

1 个答案:

答案 0 :(得分:0)

你可以这样试试吗:

let(:parent) { FactoryGirl.create(:parent) }
let(:child) { FactoryGirl.build(:child) }
subject { parent }

context "with added child object" do
  before { parent.children << child }
  its(:foo) { is.expected_to eq("bar")
end

或者,如果子对象与父对象有关系,则:

let!(:parent) { FactoryGirl.create(:parent) }
let!(:child) { FactoryGirl.build(:child, parent: parent) }
subject { parent }

context "with added child object" do
  its(:foo) { is.expected_to eq("bar")
end

让我知道结果。