How to test model's callback method independently?

后端 未结 6 1141
感情败类
感情败类 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条回答
  •  猫巷女王i
    2021-02-02 07:49

    This is more of a comment than an answer, but I put it here for the syntax highlighting...

    I wanted a way to skip the callbacks in my tests, this is what I did. (This might help with the tests that broke.)

    class Article < ActiveRecord::Base
      attr_accessor :save_without_callbacks
      after_save :do_something
    
      def do_something_in_db
        unless self.save_without_callbacks
          # do something here
        end
      end
    end
    
    # spec/models/article_spec.rb
    describe Article do
      context "after_save callback" do
        [true,false].each do |save_without_callbacks|
          context "with#{save_without_callbacks ? 'out' : nil} callbacks" do
            let(:article) do
              a = FactoryGirl.build(:article)
              a.save_without_callbacks = save_without_callbacks
            end
            it do
              if save_without_callbacks
                # do something in db
              else
                # don't do something in db
              end
            end
          end
        end
      end
    end
    

提交回复
热议问题