我有一个before_destroy
回调,如下所示:
class Component < ActiveRecord::Base
has_many :documents, through: :publications
def document_check
if documents.exists?
errors[:documents] << 'cannot exist'
return true
else
return false
end
end
测试如下:
describe '#document_check' do
let(:document) { create(:document) }
let(:component) { create(:component) }
context 'with documents' do
before do
document.components << component
end
specify { expect(component.errors).to include(:document, 'cannot exist') }
specify { expect(component.document_check).to eq true }
end
context 'without documents' do
before do
document.components = []
end
specify { expect(component.document_check).to eq false }
end
end
如果组件在文档中,我希望它引发错误,但我似乎无法正确编写它。第二次测试通过,第一次测试没有:
Diff:
@@ -1,2 +1,2 @@
-[:document, "cannot exist"]
+[]
我做错了什么?
答案 0 :(得分:1)
如何调用document_check
?如果手动(正如您第二次测试似乎建议的那样),那么您还需要为第一次指定调用它。
那是:
specify { component.document_check; expect(component.errors).to include(:document, 'cannot exist') }
这种可怕的语法,但您需要先调用该方法,然后才能检查其中的错误。
答案 1 :(得分:0)
这里是回调:
def document_check
return unless documents.present?
errors.add(:article, 'in use cannot be deleted')
false
end
这是通过测试。
describe '#document_check' do
let(:subject) { create(:component) }
let(:document) { create(:document) }
let(:count) { Component.size }
before do
document.components << subject
subject.send :document_check
end
context 'with documents raises error' do
specify do
expect(subject.errors[:article]).to be_present
end
end
context 'with documents raises correct error' do
specify do
expect(subject.errors[:article]).to include(
'in use cannot be deleted')
end
end
context 'with documents prevents deletion' do
specify do
expect { subject.destroy }.to_not change(Component, :count)
end
end
end
过了年龄但是值得。