如果属性处于活动状态,则无法删除对象 - Rspec RoR
Object can not be deleted is attribute is active - Rspec RoR
我正在尝试测试对象是否处于活动状态并且处于活动状态则无法删除。所以我的 plan_spec.rb:
里有这个
it "can not be deleted if active" do
plan = Plan.new(active: true)
r = plan.destroy
r.should_not be_valid
end
我要检查的属性名称是 'active' 并且它是布尔值,因此如果 active 为 true 那么它不能反对计划不能被删除。
有帮助吗?
在您的 Plan
class 中添加:
before_destroy :ensure_inactive
#will abort destroy if return false
def ensure_inactive
!active?
end
顺便说一句,你的规格是错误的,它不是真正的验证。你应该:
- 保存对象
- 调用销毁
- 确保它没有被破坏
可以通过使用 before_destroy
回调来实现,如果记录不能被销毁,回调将 return false
:
class Plan < ActiveRecord::Base
# ...
before_destroy :check_if_active
# ...
private
def check_if_active
!active?
end
end
使用此解决方案,您还应该重写测试,因为您不应该检查有效性:
it 'can not be deleted if active' do
plan = Plan.create!(active: true)
expect { plan.destroy }.to_not change { Plan.count }
end
我正在尝试测试对象是否处于活动状态并且处于活动状态则无法删除。所以我的 plan_spec.rb:
里有这个it "can not be deleted if active" do plan = Plan.new(active: true) r = plan.destroy r.should_not be_valid end
我要检查的属性名称是 'active' 并且它是布尔值,因此如果 active 为 true 那么它不能反对计划不能被删除。 有帮助吗?
在您的 Plan
class 中添加:
before_destroy :ensure_inactive
#will abort destroy if return false
def ensure_inactive
!active?
end
顺便说一句,你的规格是错误的,它不是真正的验证。你应该:
- 保存对象
- 调用销毁
- 确保它没有被破坏
可以通过使用 before_destroy
回调来实现,如果记录不能被销毁,回调将 return false
:
class Plan < ActiveRecord::Base
# ...
before_destroy :check_if_active
# ...
private
def check_if_active
!active?
end
end
使用此解决方案,您还应该重写测试,因为您不应该检查有效性:
it 'can not be deleted if active' do
plan = Plan.create!(active: true)
expect { plan.destroy }.to_not change { Plan.count }
end