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

时间:2011-05-24 16:40:16

标签: ruby-on-rails rspec carrierwave

我正在使用CarrierWave将图像上传到我的Imagecollection模型,并希望测试一下,当我上传图像时,它实际上是在线提供的。当我删除图像时,它实际上已被删除。

我正在使用S3后端,所以我想在模型本身中测试它,而不必具有任何控制器依赖性,或运行集成测试。所以我需要构建url,发出HTTP reequest,并测试其返回代码。此代码不起作用,但是有一种方法可以执行与以下类似的操作:

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

3 个答案:

答案 0 :(得分:1)

我不熟悉CarrierWave,你应该测试你的代码,而不是它依赖的任何外部库或服务。换句话说,你想测试你的课程,而不是S3。我建议模拟你的模型对S3进行的调用,以验证它是否正确。

答案 1 :(得分:0)

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

相反,测试image_url是否合适:

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

答案 2 :(得分: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