使用Capybara和Rspec测试将文件上传到S3的Carrierwave。

11

我已经按照这个Railscast的方法将carrierwave文件上传到了Amazon s3。

但是我在测试时遇到了一些问题。我可以使用Capybara附加一个文件,但当我点击上传按钮时,它没有重定向到正确的操作。我通过save_and_open_page进行了检查,它显示的是主页。

当我在浏览器中测试时,一切正常,但有关s3上载的信息确实添加到了url中 (截图)。不确定为什么在测试中不起作用。

以下是一些相关文件:

example_spec.rb - https://gist.github.com/leemcalilly/1e159f1b93005b8113f2

initializers/carrierwave.rb - https://gist.github.com/leemcalilly/924e8755f7c76ecbf5cf

models/work.rb - https://gist.github.com/leemcalilly/cfda1a7f15d87dbab731

控制器/works_controller.rb - https://gist.github.com/leemcalilly/7fca5f2c81c6cb4de6bc

如何使用capybara和rspec测试这种类型的表单?

1个回答

16

好的,我已经搞清楚了。关键在于CarrierWaveDirect:

https://github.com/dwilkie/carrierwave_direct#using-capybara

我需要将以下这行代码添加到我的spec_helper.rb中:

include CarrierWaveDirect::Test::CapybaraHelpers

然后我的测试需要使用这些CarrierWaveDirect匹配器:

attach_file_for_direct_upload("#{Rails.root}/spec/support/images/example.jpg") upload_directly(ImageUploader.new, "Upload Image")

因此,最终通过的测试看起来是这样的:

it "creates a new work with a test image" do
    client = FactoryGirl.create(:client)
    work = FactoryGirl.build(:work)
    visit works_path
    attach_file_for_direct_upload("#{Rails.root}/spec/support/images/example.jpg")
    upload_directly(ImageUploader.new, "Upload Image")
    fill_in "Name", :with => work.name
    select("2012", :from => "work_date_1i")
    select("December", :from => "work_date_2i")
    select("25", :from => "work_date_3i")
    select(client.name, :from => "work_client_ids")
    fill_in "Description", :with => work.description
    fill_in "Service", :with => work.service
    save_and_open_page
    check "Featured"
    click_button "Create Work"
    page.should have_content("Work was successfully created.")
end

我还需要将这个代码添加到我的 initializers/carrierwave.rb 文件中:

if Rails.env.test?
    CarrierWave.configure do |config|
      config.storage = :file
      config.enable_processing = false
    end
end

与其嘲笑对雾的反应或测试上传至s3,我只是在测试环境中关闭了上传至s3。


对于那些像我一样卡住了,而且所有的东西都和这个答案一样的人,我只想提醒一下:我必须在测试中启用js才能使其正常工作。 - rmaspero

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接