正确使用shared_examples_for的方法

时间:2012-06-15 21:34:47

标签: ruby-on-rails rspec

我可能对shared_examples_for应该做什么有缺陷的理解,但是请听我说。

基本上,我有一个公共导航栏,显示在论坛的index页面和new页面中。所以我希望导航栏的测试能够同时针对index页面和new页面执行。我希望下面使用shared_examples_for的代码可以实现这一点。但是发生了什么,shared_examples_for中的测试用例根本没有运行。要检查我是否在shared_examples_for范围内创建了失败的测试用例,但测试没有失败。

我做错了什么?

require 'spec_helper'

describe "Forums" do

  subject { page }

  shared_examples_for "all forum pages" do

    describe "should have navigation header" do
      it { should have_selector('nav ul li a', text:'Home') }
      it { should have_selector('nav ul li a', text:'About') }
    end
  end

  describe "Index forum page" do
    before { visit root_path }
    ...
  end

  describe "New forum page" do
    before { visit new_forum_path }
    ...
  end

end

2 个答案:

答案 0 :(得分:12)

这是将这些事物捆绑在一起的一种很好的意图揭示方式:

shared_examples_for 'a page with' do |elements|
  # the following two would be navs for a page with
  it { should have_selector 'h1', text: 'About' }
  it { should have_selector 'a', text: 'Songs' }
  # these would be dynamic depending on the page
  it { should have_selector('h1',    text: elements[:header]) }
  it { should have_selector('title', text: full_title(elements[:title])) }
end

describe "About" do
  it_behaves_like 'a page with', title: 'About', header: 'About Header' do
    before { visit about_path }
  end
end

describe "Songs" do 
  it_behaves_like 'a page with', title: 'Songs', header: 'Songs Header' do
    before { visit songs_path }
  end
end

答案 1 :(得分:7)

不确定您的问题是什么,但是共享示例中的describe块有多必要?那是我的第一次尝试。

此代码适用于我。

shared_examples_for 'all pages' do
  # the following two would be navs for all pages
  it { should have_selector 'h1', text: 'About' }
  it { should have_selector 'a', text: 'Songs' }
  # these would be dynamic depending on the page
  it { should have_selector('h1',    text: header) }
  it { should have_selector('title', text: full_title(title)) }
end

describe "About" do
  before { visit about_path }

  let(:title) {'About'}
  let(:header) {'About Site'}

  it_should_behave_like 'all pages'
end

describe "Songs" do 
  before { visit songs_path }

  let(:title) { 'Songs Title' }
  let(:header) { 'Songs' }

  it_should_behave_like 'all pages'
end