我正在使用Capybara 2.4.3和Rspec-Rails 3.1.0,Ruby 2.1.5和Rails 4.1.8。此测试仍然失败:
let(:attack_squad) { create :squad, user: attacker, name: 'Attack Squad' }
scenario 'attacker has available attack squad' do
visit '/account/battles/new'
save_and_open_page
expect(page).to have_select 'Squad', options: [attack_squad.name]
end
使用save_and_open_page
,我能够看到正在生成此HTML:
<select id="battle_squad_id" name="battle[squad_id]">
<option value="194">Attack Squad</option>
<option value="192">Default Squad</option>
</select>
这是失败的消息:
Battle Management attacker has available attack squad
Failure/Error: expect(page).to have_select 'Squad', options: [attack_squad.name]
expected to find select box "Squad" with options ["Attack Squad"] but there were no matches. Also found "Attack Squad Default Squad", which matched the selector but not all filters.
# ./spec/features/battle_spec.rb:31:in `block (2 levels) in <top (required)>'
# -e:1:in `<main>'
我的格式与demonstrated in the capybara spec on GitHub相同。如果我将期望改为:
expect(page).to have_select 'Squad'
能够找到选择框并成功通过。如果我将options:
值设置为数组以外的任何值,则会在sort
方法上出现错误。我错过了什么?
答案 0 :(得分:3)
在测试选择列表的存在时,有两个与选项相关的过滤器:
测试失败,因为期望HTML没有“Default Squad”选项:
<select id="battle_squad_id" name="battle[squad_id]">
<option value="194">Attack Squad</option>
</select>
您需要指定所有预期的选项:
let(:attack_squad) { create :squad, user: attacker, name: 'Attack Squad' }
let(:default_squad) { create :squad, user: attacker, name: 'Default Squad' }
scenario 'attacker has available attack squad' do
visit '/account/battles/new'
save_and_open_page
expect(page).to have_select 'Squad', options: [attack_squad.name, default_squad.name]
end
或者,如果您只关心一个选项,请使用:with_options过滤器:
let(:attack_squad) { create :squad, user: attacker, name: 'Attack Squad' }
scenario 'attacker has available attack squad' do
visit '/account/battles/new'
save_and_open_page
expect(page).to have_select 'Squad', with_options: [attack_squad.name]
end