0

Trying to do a dynamic test suite and re-use function definitions. I have a form where you can pick different types of ways that someone can contact you, and the page will display differently based on the method of contact. I am trying to do

When /^I click the (.*) return type$/ do |response|
  on_page(ContactUsPage).response unless @browser.url.include?("contactBy=#{response}")

This will take the current type of response and click the link unless the url includes "contactBy=" and the response type (meaning you're already on the page and there is no link to click)

I have a page object class (ContactUsPage) that has links for the different methods (email, phone, fax, postal)

the problem i'm having is with the ContactUsPage.response response is getting injected into the browser check, but it's looking for a method "response" inside ContactUsPage instead of injecting the method.

The method should call ContactUsPage.email or ContactUsPage.fax or ContactUsPage.phone depending on the method passed into the function.

Matt Westlake
  • 3,499
  • 7
  • 39
  • 80

1 Answers1

1

You can use Ruby's send method to invoke a method dynamically:

on_page(ContactUsPage).send(response)

send's first argument is a string or symbol with the method name to be invoked; any further arguments are passed to the method itself. For example, foo.send(:bar, "baz") is equivalent to foo.bar("baz")

If you want to call a method that starts with the variable name (email_element or similar), you just need to do a quick string interpolation:

on_page(ContactUsPage).send("#{response}_element")
# equivalent to `on_page(ContactUsPage).email_element` when response == "email"
Andrew Haines
  • 6,574
  • 21
  • 34
  • can you use this method while using the _element attribute? on_page(ContactUsPage).send(response)_element.exists?.should be_true is giving me an error after (response) "expected end of line" – Matt Westlake Jan 11 '13 at 16:09
  • Yeah, that isn't valid Ruby syntax. `send` needs the full name of the method you expect it to invoke. See my edited answer for the correct approach. – Andrew Haines Jan 11 '13 at 16:15
  • i don't think your understanding the _element part. _element is a function given to you by page object. Example: link(:email,x). if you use email, you get the value of x, email_element returns the element from the page – Matt Westlake Jan 11 '13 at 18:15
  • I'm pretty sure I understood. You want to call `email_element`, `fax_element`, and so on, right? `send("#{response}_element")` does exactly that. – Andrew Haines Jan 11 '13 at 18:58