2013-10-22 87 views
0

我有以下rspec測試,並且我正在嘗試在其中存根API方法。我在FactoryGirl的trait中定義了stub,並在(:build)回調之後使用。Rspec stubbing在FactoryGirl的特質

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 

這裏的工廠:

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 

成株從未發生和RSpec測試失敗。然而,一切正常需要,如果我刪除一個特點,簡單地離開:

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 

回答

0

打樁像這樣FactoryGirl不屬於,你應該將RSpec的測試內部磕碰。

+0

是的,但我需要分享它在不同型號的測試之間 –

+0

我其實也是這麼認爲,但後來我讀了http://stackoverflow.com/questions/9072338/should-i-stub-the-model-in -factory-girl-or-the-spec-file-while-testing,並且有點決定嘗試 –