[英]Testing after_hook with Rspec
我有标签系统和自动递增问题计数字段,它属于标签。 我正在使用Mongoid。
问题模型:
class Question
has_and_belongs_to_many :tags, after_add: :increment_tag_count, after_remove: :decrement_tag_count
after_destroy :dec_tags_count
...
private
def dec_tags_count
tags.each do |tag|
tag.dec_questions_count
end
end
和标签模型:
class Tag
field :questions_count, type: Integer,default: 0
has_and_belongs_to_many :questions
def inc_questions_count
inc(questions_count: 1)
end
def dec_questions_count
inc(questions_count: -1)
end
当我手动在浏览器中对其进行测试时,它可以正常工作;在添加或删除标签时,它会递增和递减tag.questions_count字段,但是我对问题模型after_destroy挂钩的测试总是会失败。
it 'decrement tag count after destroy' do
q = Question.create(title: 'Some question', body: "Some body", tag_list: 'sea')
tag = Tag.where(name: 'Sea').first
tag.questions_count.should == 1
q.destroy
tag.questions_count.should == 0
end
expected: 0
got: 1 (using ==)
it {
#I`ve tried
expect{ q.destroy }.to change(tag, :questions_count).by(-1)
}
#questions_count should have been changed by -1, but was changed by 0
需要帮忙...
这是因为您的tag
仍引用原始Tag.where(name: 'Sea').first
。 我相信您可以在销毁以下问题后使用tag.reload
(无法尝试确认),如下所示:
it 'decrement tag count after destroy' do
...
q.destroy
tag.reload
tag.questions_count.should == 0
end
但是比这更好的是更新tag
以指向q.tags.first
,我相信这是您想要的:
it 'decrement tag count after destroy' do
q = Question.create(title: 'Some question', body: "Some body", tag_list: 'sea')
tag = q.tags.first # This is going to be 'sea' tag.
tag.questions_count.should == 1
q.destroy
tag.questions_count.should == 0
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.