RSpec - testing multiple expectations across routes

224 views Asked by At

I'm attempting to use shared_examples as a way to repeat expectations across multiple routes. In particular, I want to test whether some static assets in my header and footer are loading. However, I get an error saying that:

RSpec::Core::ExampleGroup::WrongScopeError: `it_behaves_like` is not available from within an example (e.g. an `it` block) or from constructs that run in the scope of an example (e.g. `before`, `let`, etc). It is only available on an example group (e.g. a `describe` or `context` block).

Now, I'm not sure how to remedy this. This is my current setup.

shared_examples_for 'a page' do 
    describe 'should load static assets' do 
        it 'header, footer and icons' do 
            expect(page).to have_css 'footer.footer'                
            expect(page).to have_css '#navbar-brand'                
            brand = page.first(:css, '#navbar-brand')
            visit brand[:src]                                       
            expect(page.status_code).to be 200 
        end
    end
end


describe 'site pages should load static assets on requests', { :type => :feature } do 

after :all do 
    it_behaves_like 'a page'
end

it 'home page' do
    visit '/'
    expect(page).to have_css 'div#main-menu a', count: 5 
    page.all('link[rel~="icon"]').each do |fav|             
        visit fav[:href]
        page.status_code.should be 200
    end 
    expect(page).to have_css 'div#main-menu'
    ...     
end

it 'about page should have icons, footer and a header' do 
    visit '/about'
    ...
end 

end

Another attempt was this:

describe 'home page' do 
    it_behaves_like 'a page'
end 

Both fail for the same reason above. So, if I want to check the same things on every page, what is a better solution?

1

There are 1 answers

1
Andrew Kozin On BEST ANSWER

In RSpec 3 this should work

require 'spec_helper'

shared_examples 'a page' do 
  it 'has a header' do
    expect(page).to have_css 'footer.footer'
  end

  it 'has a brand' do       
    expect(page).to have_css '#navbar-brand'
  end

  it 'points out to brand page' do
    brand = page.first(:css, '#navbar-brand')
    visit brand[:src]                                      
    expect(page.status_code).to be 200 
  end
end

describe 'home page' do
  before { visit '/' }      

  it_behaves_like 'a page'

  it 'does something else' do
    # ...
  end
end

Alternatively you could use a block

describe 'home page' do
  it_behaves_like 'a page' do
    before { visit '/' }
  end
end