Using Given/Let w/ Feature/Scenario in Capybara
capybara, rspec, ruby, ruby-on-rails
Solution
`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 for `describe ..., :type => :feature`, `background` is an alias for `before`, `scenario` for `it`, and `given/given!` aliases for `let/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.
Problem
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 ```