Reputation: 2658
I'd like to set a variable using "given" (or "let") that is accessible by all of the "features" within my spec.rb file. How do I do this? Where should the "given" statement be located within the file? Thanks!
require 'spec_helper'
feature "Home page" do
given(:base_title) { "What Key Am I In?" }
scenario "should have the content 'What Key Am I In?'" do
visit '/static_pages/home'
expect(page).to have_content('What Key Am I In?')
end
scenario "should have the title 'What Key Am I In? | Home'" do
visit '/static_pages/home'
expect(page).to have_title("#{base_title}")
end
scenario "should not have a custom page title | Home'" do
visit '/static_pages/home'
expect(page).not_to have_title("| Home")
end
end
feature "About page" do
scenario "should have the content 'About'" do
visit '/static_pages/about'
expect(page).to have_content('About')
end
scenario "should have the title 'What Key Am I In? | About'" do
visit '/static_pages/about'
expect(page).to have_title('What Key Am I In? | About')
end
end
Upvotes: 3
Views: 6204
Reputation: 29439
given/let
calls are used at the top of a feature/describe/context
block and apply to all contained feature/describe/context
or scenario/it
blocks. In your case, if you have two separate feature
blocks, you'd want to enclose them in a higher level feature/describe/context
block and place whatever given/let
calls you want to apply to all at the higher level.
To quote the capybara documentation for use in RSpec:
feature
is in fact just an alias fordescribe ..., :type => :feature
,background
is an alias forbefore
,scenario
forit
, andgiven/given!
aliases forlet/let!
, respectively.
Further, in RSpec, describe
blocks (whether expressed through describe
, context
or the Capybara alias feature
) can be nested arbitrarily deeply. In Cucumber, by contrast, feature
can only exist at the top level of the spec.
You can Google "rspec nested describe" for more info.
Upvotes: 11
Reputation: 24815
You have to use context
within feature
to solve your problem.
feature 'Static page' do
given(:base_title) { "What Key Am I In?" }
context 'Home page' do
# code
end
context 'About page' do
# code
end
end
Two side notes:
context
in Capybara DSL, you can use it directly.Upvotes: 0