在Capybara中使用Given/Let w/Feature/Scenario

jac*_*n09 2 ruby rspec ruby-on-rails capybara

我想使用"given"(或"let")设置一个变量,该变量可以通过spec.rb文件中的所有"功能"访问.我该怎么做呢?"给定"声明应该放在文件中的哪个位置?谢谢!

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
Run Code Online (Sandbox Code Playgroud)

Pet*_*vin 8

given/let调用在feature/describe/context块的顶部使用并适用于所有包含feature/describe/contextscenario/it块.在您的情况下,如果您有两个单独的feature块,则需要将它们包含在更高级别的feature/describe/context块中,并将given/let要应用的任何调用放置在更高级别的所有调用中.

引用在RSpec中使用的水豚文档:

feature实际上只是别名describe ..., :type => :feature,分别background是for before,scenariofor itgiven/given!aliases的别名let/let!.

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

您可以通过Google"rspec nested describe"获取更多信息.