Skip to content

Instantly share code, notes, and snippets.

@hisapy
Created July 25, 2015 17:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hisapy/0cbd7898334b386afa84 to your computer and use it in GitHub Desktop.
Save hisapy/0cbd7898334b386afa84 to your computer and use it in GitHub Desktop.
Scoping in rspec view specs
##
# Inspired in:
# https://github.com/robinroestenburg/tamingthemindmonkey-sinatra/blob/master/posts/2011-11-07-capybara-matchers-and-scoping-in-view-specs.markdown
# and
# https://github.com/jnicklas/capybara/blob/d087965f8110f4098a11f52bb18edea88df277ac/lib/capybara/session.rb#L281
# I created my own nestable version of within() scope matcher
#
# Just put this in spec/support/view_helpers.rb
#
# Examples
# # Inside a view spec
# before do
# render
# end
#
# it 'renders each @client.sales.includes(sale_items)' do
# within 'section.panel.client_sales' do
# within 'div.panel-heading' do
# expect(rendered).to have_css('h4', text: /#{t('sale.attributes.id')}.*#{sale.id} /)
# end
# end
# end
#
module ViewHelpers
def within(selector)
begin
if scopes.empty?
scopes << Capybara.string(rendered).find(selector)
else
scopes << rendered.find(selector)
end
yield
ensure
scopes.pop
end
end
def rendered
scopes.last() || @rendered
end
def scopes
@scopes ||= []
end
end
RSpec.configure do |c|
c.include ViewHelpers, type: :view
end
@twalpole
Copy link

in rendered its probably better to call super rather than directly accessing the instance variable

@hisapy
Copy link
Author

hisapy commented Jul 27, 2015

I don't think so, that line is the one that creates the scoping trick and also as far as I know this is mixin and not a subclass.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment