4

我可能对应该做什么有一个有缺陷的理解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
4

2 回答 2

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
于 2012-06-19T03:15:28.767 回答
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
于 2012-06-15T21:39:37.337 回答