简体   繁体   中英

How to test a file attach with rspec in a rails project?

I put a file upload tag in my view source:

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

I want to test if user select a file and click submit button, then redirect to next page. Here is my spec source:

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

But after I run this spec test, it said:

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

This is usually because the actual file field is being hidden and overlayed with a "button" or some JavaScript driven interface so it can be styled to look the same across multiple browsers. If this is the case here you generally need to execute some JavaScript, using execute_script, to override whatever css is hiding the file field so it becomes visible on the screen and then call attach_file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM