ruby-on-rails - 如何在 Capybara 中重用代码

标签 ruby-on-rails rspec capybara

在 Rails 的功能测试中,我有一堆带有重复结构的代码。我想通过重用结构来完善我的规范。有什么建议?

一个例子是:

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 中定义一个自定义匹配器,但是当我添加 within 时块,它似乎不起作用。我的猜测是 within特定于 Capybara,不能在 RSpec 中的自定义匹配器中使用。

最佳答案

为什么不将公共(public)代码分解为模块中的辅助方法。然后您可以将该模块包含在您的 spec_helper.rb 文件中

我通常将 user_login 等常用代码放在 中的文件中的此类模块中。规范/支持 文件夹

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

规范/支持/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

关于ruby-on-rails - 如何在 Capybara 中重用代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26352251/

相关文章:

ruby-on-rails - 重新请求作业和 rspec

testing - cucumber vs capybara

ruby-on-rails-3 - selenium webdriver 2.25.0 支持的火狐版本

ruby-on-rails - 如何使用 fb_graph2 从 facebook 检索用户的电子邮件、名字和姓氏?

ruby-on-rails - 编写脚本来填充 database.yml 文件并需要正则表达式来识别特定的留置权

ruby-on-rails - 如何查找客户和用户参与 Ruby on Rails 的所有项目

ruby-on-rails - Capybara:ElementNotFound:无法在多部分表单上找到字段名称

ruby-on-rails - 测试以不同格式响应的 Rails Controller

ruby - 如何在不同文件中使用 Rspec shared_examples?

unit-testing - TDD 中驱动程序和 stub 之间的区别