繁体   English   中英

如何从 Rspec 中的 model 规范测试 HTTP 请求

[英]How can I test an HTTP request from a model spec in Rspec

我正在使用 CarrierWave 将图像上传到我的 Imagecollection model,并且想测试当我上传图像时,它实际上是在线可用的。 而且当我删除图像时,它实际上被删除了。

我正在使用 S3 后端,所以我想在 model 本身中进行测试,而不必有任何 controller 依赖项或运行集成测试。 所以我需要构造 url,发出 HTTP 请求,并测试它的返回码。 此代码不起作用,但有没有办法执行类似于以下的操作:

describe "once uploaded" do
  subject {Factory :company_with_images} 

  it "should be accessible from a URL" do
    image_url = subject.images.first.image.url
    get image_url                                   # Doesn't work
    response.should be_success                      # Doesn't work
  end
end

编辑:

我最终将它添加到我的 Gemfile

gem rest-client

并使用:fog 后端进行我的测试。 理想情况下,我可以在测试期间更改后端,例如

before do
  CarrierWave.configure do |config|
     config.storage = :fog
  end
end

describe tests
end

after do
  CarrierWave.configure do |config|
     config.storage = :end
  end
end

但这似乎并没有真正做任何事情。

describe "once uploaded" do
  describe "using the :fog backend" do
    subject {Factory :company_with_images} 

    # This test only passes beecause the S3 host is specified in the url.
    # When using CarrierWave :file storage, the host isn't specified and it
    # fails
    it "should be accessible from a URL" do
      image_url = subject.images.first.image.url
      response = RestClient.get image_url
      response.code.should eq(200)
    end
  end

  describe "using the :file backend" do
    subject {Factory :company_with_images} 

    # This test fails because the host isn't specified in the url
    it "should be accessible from a URL" do
      image_url = subject.images.first.image.url
      response = RestClient.get image_url
      response.code.should eq(200)
    end
  end
end

我不熟悉 CarrierWave,您应该测试您的代码,而不是它所依赖的任何外部库或服务。 换句话说,您想测试您的 class,而不是 S3。 我建议 mocking 您的 model 对 S3 的调用以验证它是否正确。

除非文件实际上传到 s3,否则您无法测试 s3。 在carrierwave中,默认情况下,它不会上传到s3。

相反,测试 image_url 是否正确:

image_url = subject.images.first.image.url
image_url.should == "http://.....'

我最终重新定义了规范如下

  describe "using the :fog backend" do
    subject {Factory :company_with_images} 

    it "should be accessible from a URL" do
      image_url = subject.images.first.image.url
      rest_response(image_url).code.should eq(200)
    end
  end

有了这个帮手

def rest_response url
  # https://github.com/archiloque/rest-client
  RestClient.get(url){|response, request, result| response }
end

并使用 restclient gem

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM