Should I stub the model in Factory girl or in the spec file while testing?

前端 未结 4 2018
深忆病人
深忆病人 2021-02-18 12:39

Almost every spec file I come accross I end up writing stuff like:

  before :each do
    @cimg = Factory.build :cimg_valid
    @cimg.stub(:validate_img).and_retu         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-18 13:43

    @fkreusch's answer works great until you use the new RSpec expect() syntax (3.0+)

    Putting this into rails_helper.rb works for me:

    FactoryBot::SyntaxRunner.class_eval do
      include RSpec::Mocks::ExampleMethods
    end
    

    In the OP's example, you can now do:

    FactoryBot.define do
      factory :cimg_for_testing_tags do
    
        ... # Factory attributes
    
        after(:build) do |cimg|
          allow(cimg).to receive(:validate_img) { true }
        end
      end
    end
    

    Credit: github.com/printercu, see: https://github.com/thoughtbot/factory_bot/issues/703#issuecomment-83960003

提交回复
热议问题