I'm using Cucumber with a page object similar to the simplified version shown below. I need to do some quite complex parsing of the HTML, so I'd like to be able to unit test the page object in isolation using RSpec against an HTML fixture, but I'm a bit stuck about to do this. I'm guessing that I need to stub something in Capybara, and pass it in as a dependency?
class SomePage
def header
session.find('h1').text
end
def title
session.find('title').text
end
开发者_StackOverflowprivate
def session
@session ||= Capybara.current_session
end
end
To answer my own question, I discovered Capybara has a #string method which accepts a chunk of HTML and returns a:
Capybara::Node::Simple which exposes all Capybara::Node::Matchers and Capybara::Node::Finders. This allows you to query any string containing HTML in the exact same way you would query the current document in a Capybara session.
So I just added an initializer to my class to allow this node to be passed and used in place of a Capybara session. No stubbing or mocking required, and it does exactly what I need.
精彩评论