【问题标题】:Testing after_hook with Rspec使用 Rspec 测试 after_hook
【发布时间】:2013-11-21 19:49:13
【问题描述】:

我有标签系统和自动递增问题计数的字段,属于标签。我正在使用 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 字段,但我对 Question 模型 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 

需要帮助...

【问题讨论】:

    标签: ruby-on-rails rspec mongoid


    【解决方案1】:

    这是因为您的 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
    

    【讨论】:

      猜你喜欢
      • 2014-08-16
      • 2017-06-28
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多