首页 > 解决方案 > Capybara/Rspec - 有没有办法在点击提交之前测试输入框是否已填写?

问题描述

我正在学习 RSpec 和 Capybara 并尝试测试用户是否可以导航到登录页面(由 Devise 提供支持)并成功登录。成功登录后,测试没有看到应有的页面。使用浏览器时,如果没有输入,则返回登录页面。我正在使用 Rails 5。

login_spec.rb

require 'spec_helper'
require 'rails_helper'
RSpec.feature "Logging in a User" do
    scenario "Logging in user shows special content" do
        visit "/"
        click_link "Sign In"    

        page.should have_content("Password")

        #fill in login information
        page.fill_in 'Email', with: 'admin@example.com'
        page.fill_in 'Password', with: 'some_password'
        click_on 'Log in'

        page.should have_no_content("Wait for the text which is available in the sign in page but not on next page")
        page.should have_content('User:')
        expect(page.current_path).to eq(root_path)
    end
end

水豚错误信息:

  1) Logging in a User Logging in user shows special content
     Failure/Error: page.should have_content('User:')
       expected to find text "User:" in "Log in\nEmail\nPassword\nRemember me\nSign up Forgot your password?"
     # ./spec/features/login_spec.rb:17:in `block (2 levels) in <top (required)>'

标签: ruby-on-railsrspeccapybara

解决方案


是的,您可以检查一个字段是否已用have_field匹配器填写

expect(page).to have_field('Email', with: 'admin@example.com')

将验证该页面是否有一个带有“电子邮件”标签的字段和一个填充值为“admin@example.com”的字段。

这不是您当前问题的原因,但是您混合 RSpecshouldexpect语法是否有原因?你真的应该坚持一个,最好是'期待新代码 - 所以

expect(page).to have_content("Password")
expect(page).not_to have_content("Wait for the text which is ...

代替

page.should have_content("Password")
page.should have_no_content("Wait for the text which is ...

另外 - 你几乎不应该使用与 Capybara 相关的任何东西的普通 RSpec 匹配器(eq等),而应该使用 Capybara 提供的匹配器

expect(page).to have_current_path(root_path)

代替expect(current_path)...


推荐阅读