0

I have following rspec test, and i am trying to stub api method inside it. I define stub inside FactoryGirl's trait and use after(:build) callback.

  describe '#get_json_from_api' do
    let(:output_file) { video_file.json_path }
    context "when api works" do
      around(:each) do |rspec_test|
        File.delete(output_file) if File.exists?(output_file)
        rspec_test.run
        File.delete(output_file) if File.exists?(output_file)
      end
      let!(:searched_video_file) {
        create(:video_file, :stub_api)
        video_file.get_json_from_api
        video_file
      }
      it { expect(File.size?(output_file)).to be > 0 }
    end
  end

Here's the factory:

 factory :video_file do
    trait :stub_api do
      after(:build) do |vf|
        vf.stub(:get_json_from_api){
          puts "i am callled!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
          File.open(vf.json_path, "w") do |f|
           f.write ["some data","more data"].to_json
          end
        }
      end
    end
 end

Stubbing never happens and rspec test fails. However, everything works as needed if I remove a trait and leave simply:

 factory :video_file do
      after(:build) do |vf|
        vf.stub(:get_json_from_api){
          puts "i am callled!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
          File.open(vf.json_path, "w") do |f|
           f.write ["some data","more data"].to_json
          end
        }
      end
 end
Pavel K.
  • 6,697
  • 8
  • 49
  • 80

1 Answers1

0

Stubbing like this doesn't belong in FactoryGirl, you should be stubbing inside your rspec test.

Winfield
  • 18,985
  • 3
  • 52
  • 65
  • yeah but i need to share it between tests which are in different models – Pavel K. Oct 22 '13 at 15:59
  • i actually thought so too but then i read http://stackoverflow.com/questions/9072338/should-i-stub-the-model-in-factory-girl-or-in-the-spec-file-while-testing and kinda decided to try – Pavel K. Oct 22 '13 at 16:01