Search code examples
rubyruby-on-rails-3capybarapageobjectssite-prism

Site Prism, Capybara: Selector with variable


I'm mucking around with the site_prism to implement a Page Object Model in capybara. It looks very interesting.

How would I specify a selector such as "[data-id='x']" where x is an integer? Something like this:

class Home < SitePrism::Page
  set_url "http://www.example.com"
  element :row, "[data-id='@id']"
end

And then in my tests:

Then /^the home page should contain a row$/ do
  @home.should have_row 1234
end

Solution

  • Because SitePrism sets the element locator when the element is defined, what you've suggested doesn't work. To achieve what you've asked for, take a look at the following:

    class Home < SitePrism::Page
      elements :rows, "tr[data-id]"
    
      def row_ids
        rows.map {|row| row['data-id']}
      end
    end
    

    Instead of mapping a single row, they're all mapped (using elements instead of element). A separate method called row_ids collects all of the rows that have 'data-id' value, maps all those values into a new array, and returns that new array.

    The tests would then contain something like:

    Then /^the home page should contain a row$/ do
      @home.row_ids.should include @id
    end
    

    ...which will check that there is a row with an ID that matches @id.

    Not as pretty, but it should work.