在 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/