如何使用WebMock在Sinatra应用程序中模拟Paperclip调用?

B S*_*ven 2 ruby rspec paperclip sinatra webmock

没有WebMock,此代码可以正常工作.

提出例外:

Paperclip::AdapterRegistry::NoHandlerError:
   No handler found for #<URI::HTTP:0x007ff3852cefb8 URL:http://www.example.com/images/foo.jpg>
# ./spec/support/api_mock.rb:34:in `process_image_for'
Run Code Online (Sandbox Code Playgroud)

测试:

let( :image_url  ) { 'http://www.example.com/images/foo.jpg'  }
...
stub_request(:post, image_url)
  .to_return(:status => 200, :body => File.read('spec/fixtures/image.jpg'), :headers => {})
...hit Sinatra app...
Run Code Online (Sandbox Code Playgroud)

api_mock.rb:

def self.process_image_for suggestion, params
  if params[:image]
    suggestion.image = URI.parse( params[:image] )  # line 34
    suggestion.save!
  end
end
Run Code Online (Sandbox Code Playgroud)

B S*_*ven 8

有用.FWIW,兼顾File.readFile.open工作:

stub_request(:post, image_url)
  .to_return(
     :status => 200,
     :body => File.read('spec/fixtures/image.jpg'),
     :headers => {}
  )
Run Code Online (Sandbox Code Playgroud)

只记得require 'webmock/rspec'在测试的顶部.


bob*_*obu 5

需要使用headers: {"Content-Type" => 'image/jpg'}Paperclip 期望的任何有效内容类型

例如。

stub_request(:get, "http://img.youtube.com/vi/123123123123/0.jpg")
  .to_return(
    status: 200,
    body:  File.read('spec/fixtures/images/sample.jpg'),
    headers: {"Content-Type" => 'image/jpg'}
  )
Run Code Online (Sandbox Code Playgroud)