如何在capybara中填写/选择一个select2
搜索框(通过ajax获取结果)。
使用最新的version 4
的select2
和最新的capybara/rspec
参与铁路项目。
在SO
和其他地方有很多关于如何使用qyxswpoi而不是Select2 3.x
的Capybara的例子,这是一个重写。
有version 4
gem支持select2的2/3/4版本。它默认使用select2版本4。如果您使用select2版本2或3,您可以将capybara-select-2用于其他版本
只需将gem添加到Gemfile中的测试组即可
configure
现在你可以在Cucumber或RSpec中使用group :test do
gem 'capybara-select-2'
end
测试助手了:
select2
更新:从版本select2 'Buy Milk', css: '#todo'
# Search options
select2 'Buy Milk', from: 'Things to do', search: true
# Create new options
select2 'Millennials', from: 'Generations', tag: true
开始CapybaraSelect2自动检测select2版本
对于4.0,看起来它们实际上简化了很多。对于单个选择,您可以只包括此辅助方法:
0.3.0
到目前为止对我有用,但我还没有尝试过更多自定义版本的选择器。
为此,您需要创建自己的支持功能(如果您想多次使用它。)
我有一个select2版本3.x.x的解决方案。这也适用于4。
为此,您需要创建帮助器def select2(value, **options)
first("#select2-#{options[:from]}-container").click
find(".select2-results__option", text: value).click
end
,此文件应如下所示:
spec/support/feature/xyz.helper.rb
从呼叫规范包括像module Feature
module XYZHelper
def select2(value, element_selector)
first("##{element_selector}").find(".select2-choice").click
find(:xpath, "//body").find(".select2-results li", text: value).click
end
end
end
。您可以像以下一样使用它:
include Feature::XYZHelper
我知道这已经过时了,但是这里的大多数答案(以及许多其他帖子)对于我来说都不适用于select2版本4及更高版本。我为它编写了自己的函数,它也适用于页面上的多选和多个select2输入。但是,您需要将select2包装在具有特定id的div中,以便找到正确的id。
select2("Text value here", "Id of selector")
使用示例:
def select2(values, id)
values.each do |val|
if page.has_no_css? ".select2-dropdown"
within(id) do
find('span.select2').click
end
end
within ".select2-dropdown" do
find('li', text: val).click
end
end
end
您必须传递一组值才能进行选择,即使它是单个选择。对于其中的每一个,它将打开所需select2的下拉列表,然后选择该值。