Rspec测试表单文件上传

时间:2014-07-17 05:05:34

标签: ruby-on-rails-4 rspec capybara

我正在尝试使用AWS S3为文件上传编写集成测试。我试图测试的行为是用户应该点击"选择文件"按钮,然后选择一个视频,然后用户应该看到视频,视频计数应该增加1.我在这里的起跑门绊倒,甚至似乎没有用户单击按钮。我使用的是s3 direct upload gem,而我用于表单的javascript是

<script id="template-upload" type="text/x-tmpl">

我的输出HTML看起来像这样

<form accept-charset="UTF-8" action="https://bucketname-bucket.s3.amazonaws.com/" data-callback-method="POST" data-callback-param="video[direct_upload_url]" data-callback-url="http://0.0.0.0:3000/videos" enctype="multipart/form-data" id="s3-uploader" method="post">
***some AWS stuff***
<input id="file" multiple="multiple" name="file" type="file">

因此,如果您真正转到该页面,则会出现一个按钮,其中显示&#34;选择文件。&#34;如果我点击它,它可以让我选择要上传的文件。但是,当我输入rspec时

click_button "Choose Files"
它说它无法找到按钮。所以显而易见的问题是,如何让它假装点击按钮?

1 个答案:

答案 0 :(得分:4)

您并没有真正提供有关您的表单的任何内容在Ruby和表单生成的HTML或您编写的测试,所以我将给您一个例子。

  let(:user) { FactoryGirl.create(:user) }
  let!(:project) { FactoryGirl.create(:project) }
  before(:each) do
    sign_in_as(user)
  end

  scenario 'a registered user logins and creates a new music project' do
    count = Project.all.count
    visit new_project_path

    fill_in 'Title', with: "Chillwave Song"
    fill_in 'Description', with: "I started this after being inspired by a Tycho concert"
    attach_file('project[project_file]', File.join(Rails.root, '/spec/support/project.zip'))

    click_button('Submit')

    expect(page).to have_content('Project created successfully!')
    expect(page).to have_content('I started this after being inspired by a Tycho concert')
    expect(Project.all.count).to eq(count + 1)
  end

所以有些东西应该在这里跳出来 - 你真的想在每次运行测试时上传文件吗?答案应该是否定的,那么你如何假装&#39;这个上传过程?真正最好的建议是在你的工厂中使用它:

FactoryGirl.define do
  factory :attachment do
    file ActionDispatch::Http::UploadedFile.new(:tempfile => File.new("#{Rails.root}/spec/support/project.zip"), :filename => "project.zip")
  end
end