Last active
October 10, 2019 17:11
-
-
Save tennety/f6934fb83125a393cb7a0c4e32ffc81a to your computer and use it in GitHub Desktop.
Light weight page objects for HTML strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# If you need to simply test an HTML string for content, | |
# but don't want (or have) an entire Capybara session to | |
# render it, Capybara gives you a way to wrap the HTML in | |
# a Capybara::Node::Simple object with the Capybara.string | |
# class method. With a little Ruby sprinkled on top, you | |
# can have a lightweight PageObject pattern for your tests | |
module Pages | |
class Base < DelegateClass(Capybara::Node::Simple) | |
include RSpec::Matchers | |
class << self | |
def attribute(name, selector) | |
define_method name do | |
find(selector) | |
end | |
end | |
end | |
def initialize(html_string) | |
super(Capybara.string(html_string)) | |
end | |
end | |
class MyRenderedPage < Base | |
attribute :additional_info, ".additional-info" | |
attribute :instructions, ".instructions" | |
attribute :terms, ".terms" | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Then in your spec, with this example HTML string: | |
# | |
html_string = <<~HTML | |
<main> | |
<div class='terms'><strong>You get three wishes.</strong></div> | |
<div class='instructions'><p>Rub the lamp with a silk cloth.</p></div> | |
<div class='additional-info'><small>Wishes cannot be returned.</small></div> | |
</main> | |
HTML | |
# | |
# You can do this: | |
RSpec.describe MyRenderedPage do | |
subject(:page) { Pages::MyRenderedPage.new(html_string) } | |
it "displays additional info" do | |
expect(page.additional_info).to have_content("Wishes cannot be returned.") | |
end | |
it "displays instructions" do | |
expect(page.instructions).to have_content("Rub the lamp with a silk cloth.") | |
end | |
it "displays terms" do | |
expect(page.terms).to have_content("You get three wishes.") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment