2

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
4

2 回答 2

10

given/let调用在块的顶部使用feature/describe/context并应用于所有包含的feature/describe/contextscenario/it块。在您的情况下,如果您有两个单独的feature块,您希望将它们包含在更高级别的feature/describe/context块中,并将given/let您想要应用于更高级别的所有调用。

引用在 RSpec 中使用的 capybara 文档:

feature实际上只是 的别名describe ..., :type => :feature,分别background是、和的别名。beforescenarioitgiven/given!let/let!

此外,在 RSpec 中,describe块(无论是通过 还是 Capybara 别名表示describecontext可以feature任意深度嵌套。相比之下,在 Cucumber 中,feature只能存在于规范的顶层。

您可以谷歌“rspec 嵌套描述”以获取更多信息。

于 2013-07-25T18:08:11.410 回答
0

你必须使用contextinsidefeature来解决你的问题。

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

两个旁注:

  1. 将两个功能块放在一个文件中并不好
  2. Capybara DSL中没有别名context,可以直接使用。
于 2013-07-26T14:20:20.473 回答