简体   繁体   English

使用Capybara登录路径后如何测试设计

[英]How to test devise after sign in path with Capybara

I am trying to test what happens after logging in through Devise gem. 我正在尝试测试通过Devise gem登录后会发生什么。 For example, I have the controller to go to student_dashboard_path after users successfully login. 例如,在用户成功登录后,我可以让控制器转到student_dashboard_path。

How can I test this with Capybara and Rspec? 如何使用Capybara和Rspec进行测试?

I currently have this in: 我目前在:

/spec/features/user_signs_in_sees_dashboard_spec.rb /spec/features/user_signs_in_sees_dashboard_spec.rb

require 'rails_helper'

feature 'User sign in' do
  scenario 'successfully from sign in page and sees student dashboard' do
     sign_in
     visit student_dashboard_path
     expect(current_path).to eq(student_dashboard_path)
  end
end

and I have this in: 而我在:

/spec/support/features/sign_in.rb /spec/support/features/sign_in.rb

module Features
  def sign_in
    visit user_session_path
    fill_in 'Email', with: User.first.email
    fill_in 'Password', with: User.first.password
    click_button 'Log in'
  end
end

and I am getting this error message: 我收到此错误消息:

  1) User signs in successfully from sign in and sees dashboard
 Failure/Error: expect(current_path).to eq(student_dashboard_path)

   expected: "/student/dashboard"
        got: "/student/login"

I am not sure why I am not able to log in and see the student dashboard. 我不确定为什么无法登录并查看学生仪表板。

I'm leaving my original answer below for anyone still on Capybara < 2.5.0 but in 2.5.0 you can now do 我将下面的原始答案留给仍在Capybara <2.5.0以下的任何人,但是在2.5.0中,您现在可以

expect(page).to have_current_path(<expected path>)

and it will use Capybara's waiting behavior while checking for the path 它会在检查路径时使用Capybara的等待行为

---- Below is only for Capybara version < 2.5.0 ----以下仅适用于<2.5.0的Capybara版本

expect(current_path).to eq(...) doesn't wait for the path to change, it just compares to the current path at the time it's called. Expect(current_path).to eq(...)并不等待路径更改,它只是与调用时的当前路径进行比较。 If you put a sleep after the click button I bet it works. 如果您在单击按钮后睡了,我敢打赌,它可以工作。 A better solution would be to have something like 更好的解决方案是使用类似

expect(page).to have_text('You are now logged in')

after the click_button. 在click_button之后。 That would cause capybara to wait until the log in has completed, the page loads (and the logged in notice appears), and therefore until the current_path has changed too. 这将导致水豚等待登录完成,页面加载(并且出现登录通知),并因此直到current_path也更改为止。

Use capybara save_and_open_page in middle to figure out if the fields are properly set. 使用中间的save_and_open_page来确定是否正确设置了字段。 If you work on the same machine you can switch to selenium to test out on the real browser. 如果您在同一台计算机上工作,则可以切换到以在真实的浏览器上进行测试。

Also be sure that this code does not need any JS to work because default capybara matchers will not be able to run it. 另外请确保此代码不需要任何JS即可工作,因为默认的水豚匹配器将无法运行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM