RSpec:工厂在属性更改后不持久化?
RSpec: factory not persisting after attribute changes?
我是 RSpec 的新手,但我 运行 遇到了一个问题(这是在 Rails 4 fwiw 上)。我有一个简单的 model/factory 测试:
context "Scopes" do
let (:widget) {create(:core_widget)}
it ":active" do
puts "Last Created widget:"
puts pp(Core::Widget.last)
widget.type = "active"
widget.object_status_id = 15
puts "After attribute change:"
puts pp(Core::Widget.last)
#puts pp(widget.attributes)
expect(Core::Widget.active.ids).to include(widget.id)
end
end
这是在测试一个非常简单的范围:
scope :active, -> { where(type: 'active', object_status_id:
[25, 15])
很基础。但是我注意到检查(通过工厂对象的 puts
does NOT show the attribute changes (Changing
.typeto
activeand
.object_status_idto
15`)我重新打印它?
有人告诉我 let
是延迟计算的,我明白这一点....但是当我在打印时查看不同的 object_id 时,它们是完全不同的。 let
应该在同一个 it
块中仍然有相同的对象引用,对吧?
最初我认为这是一个问题,因为我在工厂创建上做 build_stubbed
。我也尝试了 let!
因为我认为这可能是问题所在。都没有用。
我认为这里发生的事情是您在内存中更新模型的属性,但没有将更改保存到您的数据库中。然后,当您的 active
范围被调用时,将对数据库进行查询,但由于您的更改尚未保存到数据库中,因此未找到预期的记录。
我建议检查各种 update*
functions 作为将更改保存到数据库的方法,或者确保调用 save
来保存更改。
例如,您可以将测试更新为:
it ":active" do
puts "Last Created widget:"
puts pp(Core::Widget.last)
widget.type = "active"
widget.object_status_id = 15
widget.save! # Add this line here to explicitly save the record to the DB
puts "After attribute change:"
puts pp(Core::Widget.last) # Now this should find the changed record in the DB as expected
expect(Core::Widget.active.ids).to include(widget.id)
end
我是 RSpec 的新手,但我 运行 遇到了一个问题(这是在 Rails 4 fwiw 上)。我有一个简单的 model/factory 测试:
context "Scopes" do
let (:widget) {create(:core_widget)}
it ":active" do
puts "Last Created widget:"
puts pp(Core::Widget.last)
widget.type = "active"
widget.object_status_id = 15
puts "After attribute change:"
puts pp(Core::Widget.last)
#puts pp(widget.attributes)
expect(Core::Widget.active.ids).to include(widget.id)
end
end
这是在测试一个非常简单的范围:
scope :active, -> { where(type: 'active', object_status_id:
[25, 15])
很基础。但是我注意到检查(通过工厂对象的 puts
does NOT show the attribute changes (Changing
.typeto
activeand
.object_status_idto
15`)我重新打印它?
有人告诉我 let
是延迟计算的,我明白这一点....但是当我在打印时查看不同的 object_id 时,它们是完全不同的。 let
应该在同一个 it
块中仍然有相同的对象引用,对吧?
最初我认为这是一个问题,因为我在工厂创建上做 build_stubbed
。我也尝试了 let!
因为我认为这可能是问题所在。都没有用。
我认为这里发生的事情是您在内存中更新模型的属性,但没有将更改保存到您的数据库中。然后,当您的 active
范围被调用时,将对数据库进行查询,但由于您的更改尚未保存到数据库中,因此未找到预期的记录。
我建议检查各种 update*
functions 作为将更改保存到数据库的方法,或者确保调用 save
来保存更改。
例如,您可以将测试更新为:
it ":active" do
puts "Last Created widget:"
puts pp(Core::Widget.last)
widget.type = "active"
widget.object_status_id = 15
widget.save! # Add this line here to explicitly save the record to the DB
puts "After attribute change:"
puts pp(Core::Widget.last) # Now this should find the changed record in the DB as expected
expect(Core::Widget.active.ids).to include(widget.id)
end