我想測試對象是否活動,它是活動的,那麼它不能被刪除。所以我有這個在我的plan_spec.rb:對象不能被刪除屬性是活動的 - Rspec RoR
it "can not be deleted if active" do plan = Plan.new(active: true) r = plan.destroy r.should_not be_valid end
我試圖檢查屬性的名稱是「積極的」,它是布爾值,所以如果主動爲真,那麼就不能反對計劃可以不被刪除。 有什麼幫助嗎?
我想測試對象是否活動,它是活動的,那麼它不能被刪除。所以我有這個在我的plan_spec.rb:對象不能被刪除屬性是活動的 - Rspec RoR
it "can not be deleted if active" do plan = Plan.new(active: true) r = plan.destroy r.should_not be_valid end
我試圖檢查屬性的名稱是「積極的」,它是布爾值,所以如果主動爲真,那麼就不能反對計劃可以不被刪除。 有什麼幫助嗎?
它可以通過使用before_destroy
回調來實現,這將返回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
因爲我們也是這樣做的,所以我想我可以upvote :) – apneadiving
在'Rspec'中更好的使用'expect {...}。改變{.....}'。 'assert_no_difference'是最小的'ActiveSupport :: Testing :: Assertions'。 –
@Зелёный你是對的,謝謝。正如你所看到的,我習慣於最小化。 –
在Plan
類,添加:
before_destroy :ensure_inactive
#will abort destroy if return false
def ensure_inactive
!active?
end
順便說一句,你的規範是錯誤的,它不是一個真正的驗證。你應該:
有沒有任何的ansers幫助你? –
我試圖測試一切,雖然我得到這行的錯誤:expect {plan.destroy} .to_not change(Plan.count)。錯誤是:TypeError:nil不是符號。感謝您的幫助 – Mil
這可能是因爲我的錯誤 - 試試這個:'expect {plan.destroy} .to_not change {Plan.count}' –