Home > Blockchain >  RSpec Capybara unable to accept alert
RSpec Capybara unable to accept alert

Time:11-08

I've got below form:

<%= form_with url: kyc_document_upload_path, multipart: true, data: { turbo_confirm: "Are you sure to upload file?" } do |f| %>
  <%= f.hidden_field :document_type, value: item %>
  <%= f.label :file, 'Upload', name: "upload_button" %>
  <%= f.file_field :file, class: "inputfile", accept: ".pdf", onchange: 'this.form.requestSubmit()' %>
<% end %>

Now I want to test this using Capybara. So what I did was:

it 'show message' do
  login_as user
  visit profile_path

  expect(page).not_to have_css '#Upload'

  attach_file("#{Rails.root}/spec/fixtures/files/sample.pdf") do
    accept_alert "Are you sure to upload file?" do
      first(:label, 'Upload').click
    end
  end
  expect(page).not_to have_table
end

But it produces me an error:

Capybara::ModalNotFound:
       Unable to find modal dialog with Are you sure to upload file?

How to accept these alert? If I remove accept_alert block to be:

it 'show message' do
  login_as user
  visit profile_path

  expect(page).not_to have_css '#Upload'

  attach_file("#{Rails.root}/spec/fixtures/files/sample.pdf") do
    first(:label, 'Upload').click
  end
  expect(page).not_to have_table
end

I've got an error:

 Selenium::WebDriver::Error::UnexpectedAlertOpenError:
   unexpected alert open: {Alert text : Are you sure to upload file?}
     (Session info: headless chrome=107.0.5304.87)

CodePudding user response:

As mentioned in my comment, it looks like the alert is being triggered by the onchange handler of the file input. That means it wouldn't be triggered until the file selection is done, which is when attach_file returns - therefore you've likely got the accept_alert in the wrong place, and instead need

accept_alert "Are you sure to upload file?" do
  attach_file("#{Rails.root}/spec/fixtures/files/sample.pdf") do
    first(:label, 'Upload').click
  end
end
  • Related