2013-11-21 101 views
0

我有用於自動遞增問題計數的標籤系統和字段,屬於標籤。我正在使用Mongoid。使用Rspec測試after_hook

問題型號:

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 

需要幫助...

回答

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 
+0

非常感謝!我開始有點緊張,因爲無法工作...... – FastIndian