我有以下 rspec 测试,我正在尝试在其中存根 api 方法。我在 FactoryGirl 的 trait 中定义了存根并使用 after(:build) 回调。
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