0

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

我正在使用 S3 后端,所以我想在模型本身中进行测试,而不必有任何控制器依赖项或运行集成测试。所以我需要构建 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
4

3 回答 3

1

I'm not familiar with CarrierWave, you should be testing your code, not any external libraries or services it depends on. In other words, you want to test your class, not S3. I suggest mocking the calls to S3 made by your model to verify that it makes all the correct ones.

于 2011-05-24T16:45:04.543 回答
0

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

相反,测试 image_url 是否正确:

image_url = subject.images.first.image.url
image_url.should == "http://.....'
于 2011-05-24T17:10:44.307 回答
0

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

  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

于 2011-06-13T04:46:16.563 回答