Is there an alias that can be used in place of "expect(page).to" in RSpec and Capybara?

Viewed 31

I'm still using the old RSpec 2 syntax that looks like this:

page.should have_text('foo')

Rather than

expect(page).to have_text('foo')

If say the should syntax becomes unsupported entirely, is there any way to build some kind alias so that I can still use the old syntax? Basically mapping page.should to expect(page).to and page.should_not to expect(page).not_to?

I think I just have a strong affinity to the old syntax in terms of readability/cleanliness of syntax. Thanks.

1 Answers

You'd probably need to monkey patch something this this method that seems pretty straightforward: https://github.com/rspec/rspec-expectations/blob/dba67987c63f551d1bf0f7877f069fa8b72d0461/lib/rspec/expectations/syntax.rb#L43:L45

def should(matcher=nil, message=nil, &block)
  ::RSpec::Expectations::Syntax.warn_about_should_unless_configured(::Kernel.__method__)
  ::RSpec::Expectations::PositiveExpectationHandler.handle_matcher(self, matcher, message, &block)
end

But which object exactly to monkey patch? Hard to tell, because page has this method, and current_scope has it as well, the former being the object of Capybara::Session class and the latter Capybara::Node::Document. What other possible objects get this should method from that module?

So, to do it properly you'd need to have very good knowledge of the Rspec and Capybara internals. When you understood it - you need to stay up to date with any future developments of this project that might influence this feature (that you are now responsible for maintaining). And if it's a commercial project - developers might find it awkward and push towards the official syntax anyway.

So it's not just a simple alias that would work forever, it's a feature to maintain. I'm not claiming it's not worth it, but you need to answer this question yourself: is it?

Related