我正在测试与Rspec一个名为解决方案,它有很多喜欢的模型。解决方案存储多少喜欢(counter_cache)。它有一个“likes_count”属性(和相应的db字段)。Rails 3和Rspec:计数器缓存列正在更新到2预期1
当我创建一个与解决方案关联的Like记录时,我期望解决方案属性“likes_count”应该从零更新为1.当我在控制台中这样做时,它可以工作。
但是当我运行规范,做同样的事情我在控制台做,它更新两次“likes_count”字段,将其设置为2
看看(控制台)WORKING:
irb(main):001:0> solution = Factory(:solution)
irb(main):004:0> solution.likes_count
=> nil
irb(main):006:0> like = Factory(:like, :likeable => solution)
=> #<Like id: 1, user_id: 2, likeable_id: 1, likeable_type: "Solution",
created_at: "2011-11-23 19:31:23", updated_at: "2011-11-23 19:31:23">
irb(main):007:0> solution.reload.likes_count
=> 1
看一看规范结果不工作:
1) Solution counter cache should be increased when a like is created
Failure/Error: subject.reload.likes_count.should be 1
expected #<Fixnum:3> => 1
got #<Fixnum:5> => 2
Compared using equal?, which compares object identity,
but expected and actual are not the same object. Use
'actual.should == expected' if you don't care about
object identity in this example.
# ./spec/models/solution_spec.rb:45:in `block (3 levels) in <top (required)>'
这里是在S佩奇:
describe "counter cache" do
let(:solution) { Factory(:solution) }
it "should be increased when a like is created" do
Factory(:like, :likeable => solution)
solution.reload.likes_count.should be 1
end
end
我看了看test.log中,我意识到,更新该计数器缓存列的数据库查询在测试中调用两次。
SQL (0.5ms) INSERT INTO "likes" ("created_at", "likeable_id", "likeable_type", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?) [["created_at", Wed, 23 Nov 2011 19:38:31 UTC +00:00], ["likeable_id", 121], ["likeable_type", "Solution"], ["updated_at", Wed, 23 Nov 2011 19:38:31 UTC +00:00], ["user_id", 204]]
SQL (0.3ms) UPDATE "solutions" SET "likes_count" = COALESCE("likes_count", 0) + 1 WHERE "solutions"."id" IN (SELECT "solutions"."id" FROM "solutions" WHERE "solutions"."id" = 121 ORDER BY id DESC)
SQL (0.1ms) UPDATE "solutions" SET "likes_count" = COALESCE("likes_count", 0) + 1 WHERE "solutions"."id" IN (SELECT "solutions"."id" FROM "solutions" WHERE "solutions"."id" = 121 ORDER BY id DESC)
Solution Load (0.3ms) SELECT "solutions".* FROM "solutions" WHERE "solutions"."id" = ? LIMIT 1 [["id", 121]]
是的,这是问题所在。非常感谢,jkronz! 这段代码导致Spork.each_run块上的问题: 'Dir [“#{Rails.root}/app/**/*。rb”]。{| f |加载f}' –
我有这个相同的问题,但我找不到它加载两次。有关如何调试的建议?我正在使用rails 4.1。谢谢。 –