Search code examples
rubytestingmethodscucumbervariable-assignment

Cucumber: variable used to complete a method in ruby


Is there an elegant way to use the variable var_name in the method below - so whichever name used as a first string in the step will be reflected at the end of the var?

Then('the {string} variable in the response should be {string}') do |var_name, value|
  var = Connection.session.**"#{var_name}"**
  raise "Expected #{var} to equal '#{value}', but was #{var}" unless var == value 
end

BR, Kamilo


Solution

  • In order to send a message with a selector you only know at runtime, you can use the Object#public_send method. public_send allows you to send any message to an object by just passing the name of the message as an argument:

    Connection.session.public_send(var_name)