正确使用shared_examples_for的方法

我可能对shared_examples_for应该做什么有一个错误的理解,但是听我说。

基本上,我有一个公共导航栏出现在index页面和论坛的new页面。 所以我希望测试导航栏能够同时执行index页面和new页面。 我希望下面的代码使用shared_examples_for来实现这一点。 但是发生的事情是, 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 

不确定你的问题是什么,但是共享示例中的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 

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

 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