Vadorequest
Vadorequest

Reputation: 17997

Test view/DOM content RSpec ruby capybara

I would like to know how test the DOM content in a view RSpec test, to know if the content exists I usually use match or have_content (match for HTML ids/classes), but here I would like to know if a div is visible or not (style display: none) and I don't know how do it.

What's the better way to check the DOM with RSpec?

I also talk about another developer and he says me that it was better to check the DOM and this kind of stuff in the feature test because the view was not good enough to do that, I would like to have another opinion about that.

Upvotes: 2

Views: 971

Answers (1)

Roman Kiselenko
Roman Kiselenko

Reputation: 44360

I test DOM element with Rspec/Capybara. I have PageObject class and include Capybara::DSL look example
in spec/support/page_object.rb:

class PageObject
  include Capybara::DSL

  def visit_page(page)
    visit(page)
    self
  end

  def have_field?(attributes)
    find_field(attributes).visible?
  end

  def have_link?(link)
    find(:xpath, "//a[@href='#{link}']").visible?
  end

  def save_and_open_page
    super
  end

  def login(model)
    fill_in 'email', with: model.email
    fill_in 'password', with: model.password
    click_on 'Submit'
  end

  def right_path?(path, page)
    visit_page(page) && current_path == path
  end
end

and spec/views/event_spec.rb:

require 'spec_helper'

feature 'test authozire page' do
  let(:login_page) { PageObject.new }
  let(:user) { FactoryGirl.create(:user) }

  scenario 'login page have field' do
    page = login_page.visit_page('/home/login')
    expect(page.have_field?('email')).to be_true
    expect(page.have_field?('password')).to be_true
    expect(page.have_link?('/users/auth/facebook')).to be_true
    expect(page.have_link?('/users/auth/vkontakte')).to be_true
  end

  scenario "user can login" do
    login_page.visit_page('/home/login').login(user)
    page = login_page.visit_page('/home/login')
    expect(page.have_link?('/search/events')).to be_true
    expect { page.have_link?('/search/users') }.to raise_error(Capybara::ElementNotFound)
    expect(login_page.visit_page('/user_profile')).to be_true
    expect(login_page.right_path?('/user_profile', '/user_profile')).to be_true
    expect(login_page.visit_page('/user_profile/edit')).to be_true
    expect(login_page.right_path?('/user_profile/edit', '/user_profile/edit')).to be_true
  end
end

Upvotes: 3

Related Questions