How to test inside iframes with cucumber / capybara

Updated . Posted . Visible to the public. Deprecated.

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.

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
Judith Roth
Last edit
Daniel Straßner
License
Source code in this card is licensed under the MIT License.
Posted by Judith Roth to makandra dev (2020-12-21 16:39)