我正在为使用paranoid2 gem的模型进行RSpec测试。这是某种偏执狂或act_as_paranoid - 用它自己的版本覆盖.delete和.destroy以及其他一些版本,这些版本将数据标记为已删除而不是删除它,直到您强制使用(forced: true)
参数。
我的应用程序运行正常,我只有rspec问题。
规格/模型/ slide_spec.rb:
describe Slide do
let (:slide) { build(:slide) }
describe "after .destroy(force: true)" do
before do
slide.save
slide.destroy(force: false)
end
it "is invisible" do
expect{slide.destroy(force: true)}.to_not change(Slide, :count)
end
it "visible if .only_deleted" do
expect{slide.destroy(force: true)}.to change(Slide.only_deleted, :count).by(-1)
end
it "visible if .with_deleted" do
expect{slide.destroy(force: true)}.to change(Slide.with_deleted, :count).by(-1)
end
end
end
rspec输出:
after .destroy(force: true)
visible if .with_deleted (FAILED - 1)
visible if .only_deleted (FAILED - 2)
is invisible (FAILED - 3)
Failures:
1) Slide after .destroy(force: true) visible if .with_deleted
Failure/Error: expect{slide.destroy(force: true)}.to change(Slide.with_deleted, :count).by(-1)
RuntimeError:
can't modify frozen Hash
# ./spec/models/slide_spec.rb:52:in `block (4 levels) in <top (required)>'
# ./spec/models/slide_spec.rb:52:in `block (3 levels) in <top (required)>'
2) same as above
3) same sa above
/app/model/slide.rb:
class Slide < ActiveRecord::Base
paranoid
...
答案 0 :(得分:4)
这是因为在模型上调用destroy后,Rails用freeze
标记内部属性哈希。此冻结哈希禁止对象进一步更改:稍后destroy(force: true)
想要删除id
,reload
想要使用数据库中的新值覆盖某些属性 - 两者都将失败。 / p>
避免此问题的唯一方法是手动重新加载对象:
describe "after .destroy(force: true)" do
before do
slide.save
slide.destroy(force: false)
@slide = Slide.with_deleted.find(slide.id) # manual reload
end
it "is invisible" do
expect{@slide.destroy(force: true)}.to_not change(Slide, :count)
end
it "visible if .only_deleted" do
expect{@slide.destroy(force: true)}.to change(Slide.only_deleted, :count).by(-1)
end
it "visible if .with_deleted" do
expect{@slide.destroy(force: true)}.to change(Slide.with_deleted, :count).by(-1)
end
end