Should I stub the model in Factory girl or in the

2019-04-03 06:45发布

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_return true
    @cimg.stub(:validate_img_url).and_return true
    @cimg.stub(:save_images).and_return true
    @cimg.stub(:process_image).and_return true
    @cimg.stub(:img).and_return true
  end

I mean, the model I get from Factory.build is completely valid. But if I don't stub that stuff it saves things in the filesystem, and validates stuff I'm not testing...

What I mean, I think it would be cleaner to do something like this:

  before :each do
    @cimg = Factory.build :cimg_for_testing_tags
  end

If stubbing within the Factory is even possible.

What is the proper way to stub the model?

4条回答
孤傲高冷的网名
2楼-- · 2019-04-03 07:11

In recent versions of factory_girl you have an after_build callback, so I believe you could define your factory like this:

FactoryGirl.define do
  factory :cimg_for_testing_tags do

    ... # Factory attributes

    after_build do |cimg|
      cimg.stub(:validate_img).and_return true
    end
  end
end

UPDATE

After factory_girl 3.3.0, the syntax has changed to following:

FactoryGirl.define do
  factory :cimg_for_testing_tags do

    ... # Factory attributes

    after(:build) do |cimg|
      cimg.stub(:validate_img).and_return true
    end
  end
end
查看更多
趁早两清
3楼-- · 2019-04-03 07:12

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

Putting this into rails_helper.rb works for me:

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

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

FactoryGirl.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_girl/issues/703#issuecomment-83960003

查看更多
Ridiculous、
4楼-- · 2019-04-03 07:12

You might also consider using FactoryGirl#build_stubbed.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-04-03 07:15

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.

查看更多
登录 后发表回答