Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 824
Zequez Avatar asked Jan 30 '12 23:01

Zequez


People also ask

What is Build_stubbed?

build_stubbed is the younger, more hip sibling to build ; it instantiates and assigns attributes just like build , but that's where the similarities end. All reactions. Sign up for free to join this conversation on GitHub.


1 Answers

@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

like image 115
Ho-Sheng Hsiao Avatar answered Nov 10 '22 13:11

Ho-Sheng Hsiao