Laura Laura - 4 months ago 23
Ruby Question

How to use a table in Cucumber with Ruby to verify data on web form

I am using Cucumber with Ruby and Watir webdriver.

What I am trying to do is verify that data that is pre-populated on a web form matches the data in a table in the features file in Cucumber. I need help in writing the Ruby code in the step definitions file. Here is what I have so far:

Cucumber feature:
Then I will be able to view my information pre-populated from IAM as follows:

|First Name/Given Name |Chimwemwe |
|Last Name/Surname |Rossi |
|Country |USA |
|Address |fdafda |
|City |fdafd |
|State |Louisana |
|Postal Code |99999 |

Then (/^I will be able to view my information pre-populated from IAM.$/) do |table|
information = table.rows_hash
information.each do |entry|
contact_info = entry [0]
if @browser.text_field(:name=>'firstName').verify_contains(contact_info[0])==true
puts "Passed"
else
puts "Failed"
end
end


I am only doing the first row for now until I get it to work. I would like it to eventually iterate through the table.

when I try to run the script all I get is this error: #table is a Cucumber::Core::Ast::DataTable.

I am fairly new to Ruby/Cucumber and this is the most complicated script I have written so far. Any help on how to do this would be really helpful. I know I need an array, but i have been looking at so much of this online, I feel like my brain is going to explode. Thanks.

Answer

Unless you have an easy way to map the Cucumber table to the Watir fields, iteration might not be useful. The simplest approach is to directly check that each field under test matches the table.

I am not sure which assertion library you are using, but as an example, the following uses the RSpec Expectations:

Then (/^I will be able to view my information pre-populated from IAM.$/) do |table|
  information = table.rows_hash

  expect(@browser.text_field(:name=>'firstName').value).to eq(information['First Name/Given Name'])
  expect(@browser.text_field(:name=>'lastName').value).to eq(information['Last Name/Surname'])
  # etc. for each field
end

Note that the test will fail at the first incorrect field. If you want to assert all of the fields at once, you can retrieve them into a Hash and compare it to the table:

Then (/^I will be able to view my information pre-populated from IAM.$/) do |table|
  form_fields = {
    'First Name/Given Name' => @browser.text_field(:name=>'firstName').value,
    'Last Name/Surname' => @browser.text_field(:name=>'lastName').value
  }
  expect(form_fields).to eq(table.rows_hash)
end
Comments