How to test model's callback method independently?

后端 未结 6 1194
感情败类
感情败类 2021-02-02 07:34

I had a method in a model:

class Article < ActiveRecord::Base
  def do_something
  end
end

I also had a unit test for this method:



        
6条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-02 07:53

    I like to use ActiveRecord #run_callbacks method to make sure callbacks are been called without need to hit database. This way it runs faster.

    describe "#save" do
      let(:article) { FactoryBot.build(:article) }
      it "runs .do_something after save" do
        expect(article).to receive(:do_something)
        article.run_callbacks(:save)
      end
    end
    

    And to test the behavior of #do_something you add another test specifically for that.

    describe "#do_something" do
      let(:article) { FactoryBot.build(:article) }
      it "return thing" do
        expect(article.do_something).to be_eq("thing")
      end
    end
    

提交回复
热议问题