Search code examples
ruby-on-railsrubycucumberbdd

How do i get the response HTML of an entire Page from a Cucumber Step that uses Capybara?


When running my specs i get errors where Capybara couldn't find elements based on their labels and such. Then i thought i wanted the HTML, or somehow debug the errors.

This is the /features/merge.feature

#Just a test!
Scenario: Cannot merge articles when not admin
    Given I am not an admin
    When I am on the edit article page
    Then I should not see the "merge articles" form

And this is: /feature/step_definitions/merge.rb - and it only contains "Given" statements!

Given /am not an admin$/ do
  visit '/accounts/login'
  puts "TEZT"
  puts page.native
  puts page.native.text
  fill_in 'user_login', :with => 'editor_rico'
  fill_in 'user_password', :with => 'a'
  click_button 'Login'
end

Given /^I am an admin$/ do
  visit '/accounts/login'
  fill_in 'user_login', :with => 'admin_rico'
  fill_in 'user_password', :with => 'a'
  click_button 'Login'
end

Then i get this error:

Scenario: Cannot merge articles when not admin    
# features/article_merging.feature:20
Given I am not an admin                 
#features/step_definitions/article_steps.rb:39
cannot fill in, no text field, text area or password field with id, name, or label
'user_login' found (Capybara::ElementNotFound)
(eval):2:in `fill_in'
./features/step_definitions/article_steps.rb:44:in `/am not an admin$/'
features/article_merging.feature:21:in `Given I am not an admin'

Havin a rough time working with Cucumber here ..

1) Why do i get the above

2) How do i debug it, i wanna see the HTML code!


Solution

  • This errors appears when your page HTML does not contain any input or textarea element with name, id or label 'user_login'. If you add the launchy gem to your Gemfile you will be able to see how your page looks:

    In your Gemfile:

    group :test do
      gem 'launchy'
      gem 'capybara'
      ...
    end
    

    Then, inside your feature/step_definitions/merge.rb file:

    Given /^I am not an admin$/ do
      visit '/accounts/login'
      save_and_open_page
    end
    

    The save_and_open_page will open the current page in your browser, so then you can inspect the HTML and see what it looks like.

    Hope it helps! :)