如何在Capybara中重用代码 [英] How to reuse code in Capybara

查看:66
本文介绍了如何在Capybara中重用代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails的功能测试中,我有一堆重复结构的代码。我想通过重用结构来使我的规格变干。有任何建议吗?

I have a bunch of codes with repeating structures in a feature test in Rails. I would like to dry up my spec by reusing the structure. Any suggestions?

例如:

feature "Search page"
  subject { page }

  it "should display results"
    # do something

    within "#A" do
      should have_content("James")
    end
    within "#B" do
      should have_content("October 2014")
    end

    # do something else

    # code with similar structure
    within "#A" do
      should have_content("Amy")
    end
    within "#B" do
      should have_content("May 2011")
    end
  end

在首先,我尝试在RSpec中定义一个自定义匹配器,但是当我在内添加块时,它似乎不起作用。我的猜测是是特定于水豚的,不能在RSpec的自定义匹配器中使用。

At first, I tried to define a custom matcher in RSpec, but when I add within block, it did not seem to work. My guess is within is specific to Capybara, and cannot be used in custom matcher in RSpec.

推荐答案

为什么不将通用代码纳入模块的帮助器方法中。然后,您可以将该模块包含在spec_helper.rb文件中

Why not factor the common code into helper methods in a module. Then you can include that module in your spec_helper.rb file

我通常将诸如user_login之类的通用代码放入此类模块中的 spec / support 文件夹

I usually put common code like user_login in such a module in a file in the spec/support folder

spec_helper.rb

#Load all files in spec/support
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

RSpec.configure do |config|
  #some config

  config.include LoginHelper

  #more config
end

spec / support / login_helper.rb

module LoginHelper
  def do_login(username, password)
   visit root_path
     within("#LoginForm") do
       fill_in('username', :with => username)
       fill_in('password', :with => password)
      click_button('submit')
     end
   end
end

这篇关于如何在Capybara中重用代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆