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

前端 未结 4 2017
深忆病人
深忆病人 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:24

    A factory should produce "real world" objects therefore it's a bad practice (and error prone) to change behaviour (i.e. stub) in a factory.

    You can do

    let(:user) instance_double(User, FactoryGirl.attributes_for(:user))
    
    before do
      allow(user).to receive(:something).and_return('something')
    end
    

    and if your before clause gets too big you may want to extract it to a separate method or create a mock child class that overrides methods you want to stub.

提交回复
热议问题