如何在rails项目中使用rspec测试文件附加?

时间:2015-08-12 03:55:17

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

我在文件来源中添加了文件上传标记:

<%= form_tag(confirm_path, method: :post, multipart: true) do %>
  <%= file_field_tag 'my_file' %>
  <button type='submit'>Submit</button>
<% end %>

我想测试用户是否选择文件并单击“提交”按钮,然后重定向到下一页。这是我的规格来源:

require 'rails_helper'

feature 'MyTest', type: :feature do
  describe 'File test' do
    before do
      visit index_path
    end

    it 'If select a file, then go to next page' do
      attach_file 'my_file', my_real_file_path # I am sure this file exists
      click_button 'Submit'
      expect(page).to have_content('Confirm Page')
    end
  end
end

但在我运行此规范测试后,它说:

Failure/Error: attach_file 'my_file', my_real_file_path
Capybara::ElementNotFound:
  Unable to find file field 'my_file'

1 个答案:

答案 0 :(得分:0)

这通常是因为实际的文件字段被隐藏并用“按钮”或一些JavaScript驱动的界面覆盖,因此它可以被设计为在多个浏览器中看起来相同。如果是这种情况,你通常需要执行一些JavaScript,使用execute_script来覆盖任何css隐藏文件字段,以便它在屏幕上变得可见,然后调用attach_file