【问题标题】:How to use RSpec custom matcher for multiple 'should have_selector'如何为多个“应该有_选择器”使用 RSpec 自定义匹配器
【发布时间】:2013-07-04 21:22:16
【问题描述】:

正如您在阅读标题时猜到的那样,我正在使用 Rspec 来测试我的 RoR 代码。在我的测试中,我想在某些操作后验证我是否在某个页面上,并验证该页面上是否存在某些元素。为此,我使用以下代码:

# Show page title
it { should have_selector('title', text: "Button text") }

# Show form fields
it { should have_selector('input', id: "user_email") }
it { should have_selector('input', id: "user_password") }
it { should have_selector('input', id: "user_password_confirmation") }
it { should have_selector('input', value: "Schrijf me in") }

但在另一个测试中,我还想验证是否在同一页面上。我可以再次使用上面的代码,但感觉不对。

我想使用 Rspec 自定义匹配器来执行此操作。但我能找到的唯一示例需要将参数传递给匹配器,或者只能验证一个选择器。如何编写自定义匹配器来执行此操作?

【问题讨论】:

    标签: ruby-on-rails rspec2 rspec-rails


    【解决方案1】:

    如果你的测试是一样的,你想要的是shared_examples

    shared_examples 'on user home page' do
      # Show page title
      it { should have_selector('title', text: "Button text") }
    
      # Show form fields
      it { should have_selector('input', id: "user_email") }
      it { should have_selector('input', id: "user_password") }
      it { should have_selector('input', id: "user_password_confirmation") }
      it { should have_selector('input', value: "Schrijf me in") }
    end
    
    # Spec File #1
    describe 'Test one' do
      it_behaves_like 'on user home page'
    end
    
    # Spec File #2
    describe 'Test two' do
      it_behaves_like 'on user home page'
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多