In my rails app, I have a select on the navigation bar as follows:
<body>
<div id="wrapper">
<!-- Navigation -->
<nav role="navigation" style="margin-bottom: 0">
<div class="navbar-default sidebar hidden-sm hidden-xs" role="navigation">
<div class="sidebar-nav">
<ul class="nav" id="side-menu">
<li>
<h4 class="sidebar-title">SGPLAN</h4>
</li>
<li class="logo">
<form action="#">
<select name="" id="change_plan" class="form-control plan">
<option value="1" id="plan_id" selected="">first </option>
<option value="2" id="plan_id">other </option>
</select>
</form>
</li>
and javascript in application.js to load the home page when the user selects a different option.
$(document).ready(function() {
//...
$('#change_plan').on('change', function(){
var str = ''
str += $( this ).val() + " ";
setCookie("plan", str,1);
window.location.href = "/";
})
});
I have written the following test for this feature using rspec, capybara and capybara-webkit:
require 'rails_helper'
feature "Change plan", :js do
background do
login_as create(:admin_user), scope: :user
Agency.current = Agency.find_by(initials: 'SECTI').id
FactoryGirl.create(:other_plan)
Plan.current = Plan.find_by(name: 'first').id
end
scenario "User changes the current plan" do
visit "/milestones"
save_and_open_page
select('other', from: 'change_plan')
# within '#change_plan' do
# find("option[value='2']").click
# end
# find('#change_plan').find('option', text: 'other').select_option
expect(current_path).to eq("/")
end
end
save_and_open_page results in the html snippet as shown above.
The result of running the test is as follows:
Failures:
1) Change plan User changes the current plan
Failure/Error: expect(current_path).to eq("/")
expected: "/"
got: "/milestones"
(compared using ==)
# ./spec/features/plans/change_plan_spec.rb:19:in `block (2 levels) in <top (required)>'
Finished in 1 minute 1.71 seconds (files took 2.04 seconds to load)
1 example, 1 failure
If I use find('#change_plan')...
or find("option...")
(as per the commented out lines) in the test instead of the select, the result is the same.
My versions are follows (from Gemfile.lock
):
capybara (2.7.1)
capybara-webkit (1.11.1)
database_cleaner (1.5.3)
factory_girl_rails (4.7.0)
rails (4.2.5)
rspec-core (3.5.4)
rspec-expectations (3.5.0)
rspec-mocks (3.5.0)
rspec-rails (3.5.2)
and ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]
What do I need to do get this test to work? Should I be using a different test platform? We are relatively committed to rspec but less so to capybara.
Update
I finally got this working with the help of Thomas and employing multiple suggestions that he provided.
答案 0 :(得分:0)
您不应该将eq
匹配器与current_path一起使用,因为它没有等待/重试行为。这意味着您在页面有时间更改之前检查路径。而是使用Capybara提供的have_current_path匹配器
expect(page).to have_current_path('/')