Read more

How to test inside iframes with cucumber / capybara

Judith Roth
December 21, 2020Software engineer at makandra GmbH

Spreewald >= 4.1.0 includes steps for dealing with iframes:
https://github.com/makandra/spreewald#frame_stepsrb

When testing with Cucumber / Caypbara, iframes are ignored, so you can't interact with them.

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

To interact with your iframe, you have to explicitly tell your driver to use it.
You can reference your iframe either through it's id, or if none given, by it's number:

When /^(.*?) inside the (.*?). iframe$/ do |nested_step, frame_number|
  page.within_frame(frame_number.to_i) do
    step nested_step
  end
end

When /^(.*?) inside the (.*?). iframe:$/ do |nested_step, frame_number, table_or_string|
  page.within_frame(frame_number.to_i) do
    step("#{nested_step}:", table_or_string)
  end
end

Use it like this:

  Then the radio button "sample.pdf" should not be checked inside the 1. iframe
    And I should see in this order within the breadcrumb inside the 1. iframe:
      """
      Files
      Alpha
      """

However, if you have to perform lots of steps within your iframe, this can be quite tedious. Then it is easier to tell the driver to use the iframe for all following steps. You can do that with a step like this:

When('I switch to the {int}. iframe') do |frame_number|
  frames = page.find_all('iframe')
  page.driver.switch_to_frame(frames[frame_number])
end

Use it like this:

  When I switch to the 1. iframe
  Then the radio button "sample.pdf" should not be checked
    And I should see in this order within the breadcrumb:
      """
      Files
      Alpha
      """

When the iframe is removed from the DOM the driver switches back to using the regular frame again automatically. We also had cases in which this did not happen reliably. In this case you have to switch back manually:

When('I switch back from the iframe') do
  page.driver.switch_to_frame(:top)
end
Posted by Judith Roth to makandra dev (2020-12-21 17:39)