我已经设置了软删除功能(不使用Paranoia gem):用户可以被软删除,然后作用域destroy_all会永久删除所有软删除的用户。它在开发中有效,但我无法通过测试。测试使用范围进行查询,但无论如何都会销毁所有用户。
User.rb scope :only_deleted, -> { where.not(deleted_at: nil) }
中的范围查找所有软删除的用户。在控制器中,我有:
def destroy_soft_deleted
User.only_deleted.destroy_all
...
end
我尝试了这个测试(以及许多其他组合):
def setup
@user1 = users(:adam)
@user2 = users(:beth)
end
test "successful permanent deletion of all soft-deleted users" do
@user2.soft_delete
assert_difference "User.count", -1 do
delete destroy_soft_deleted_users_path
end
end
所有其他测试通过(例如@user.soft_delete
已经过测试)并且灯具很好。测试日志显示正在使用的范围,但它仍然删除了两个用户:
SELECT "users".* FROM "users" WHERE ("users"."deleted_at" IS NOT NULL)
DELETE FROM "users" WHERE "users"."id" = ?[0m [["id", 585460615]]
DELETE FROM "users" WHERE "users"."id" = ?[0m [["id", 911064266]]
这是测试结果:
"User.count" didn't change by -1.
Expected: 1
Actual: 0
Model.some_scope.destroy_all
在测试中不起作用吗?我应该使用不同的断言吗?