Home > OS >  How to convert a string to an object reference in ruby
How to convert a string to an object reference in ruby

Time:05-17

I want to take in a page name in a gherkin step then set it as an object reference (I think that's what it's called.) Then I can use that to interact with page elements. Is there an easier way to do this in ruby?

When(/^I am on the (.*) page$/) do |page|
  case page
  when "home page"
  @current_page = @home_page
  when "my account page"
  @current_page = @my_account_page
  end
end

Then

When(/^I click the (.*)$/) do |element|
 @current_page.send(element).click
end

CodePudding user response:

You can use instance_variable_get:

When(/^I am on the (.*) page$/) do |page|
  @current_page = instance_variable_get("@#{page}")
end

This will work if the page values perfect match your instance variables, e.g.

page = "my_account_page"

# The following two lines are equivalent
instance_variable_get("@#{page}")
@my_account_page
  • Related