禁用rspec测试后,如何重新启用回调?

时间:2018-08-06 22:54:05

标签: ruby-on-rails rspec

我有以下代码,但是我的其他测试方法失败了,因为:before_save回调未在单独的测试中触发。

 before do
      PropertyPerson.skip_callback :save, :before, :generate_match_input_names!, raise: false
    end

    describe :with_search_name_fuzzy do
      it 'finds the property_person' do
        property_person = property.property_people.create(person: person, match_input_search_names: ['Kamil Makski'])

        expect(PropertyPerson.with_search_name_fuzzy('KAM')).to be_present

      end
    end

2 个答案:

答案 0 :(得分:3)

skip_callback确实不是为临时使用而设计的。

一个更安全的选择是让RSpec存根您的回调方法:

allow_any_instance_of(PropertyPerson).to receive(:generate_match_input_names!).and_return(true)

答案 1 :(得分:1)

我不认为Rails允许您轻松地重新启用回调。您可以做的是重新定义被调用的方法以将其禁用:

before do
  class PropertyPerson
    alias :_orig_generate_match_input_names!, :generate_match_input_names!

    def generate_match_input_names!
      nil
    end
  end
end

并重新启用它

after do
  class PropertyPerson
    alias :generate_match_input_names!, :_orig_generate_match_input_names!
  end
end

关于alias的一件很酷的事情是,它复制了方法,而不仅仅是名称。因此,您可以使用它来恢复其原始实现,而无需重复实现本身(就像您需要使用skip_callbackset_callback一样)