ruby-on-rails - Capybara/Rspec - 有没有办法在单击提交之前测试输入框是否已填充?

标签 ruby-on-rails rspec capybara

我正在学习 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: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1b0b5bcb8bf91b4a9b0bca1bdb4ffb2bebc" rel="noreferrer noopener nofollow">[email protected]</a>'
        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

capybara 错误消息:

  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)>'

最佳答案

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

expect(page).to have_field('Email', with: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="28494c454146684d50494558444d064b4745" rel="noreferrer noopener nofollow">[email protected]</a>')

将验证页面是否有一个带有“电子邮件”标签且填充值为“[email protected]”的字段。 '.

这不是您当前问题的原因,但您混合 RSpecs shouldexpect 语法是否有原因?您确实应该坚持使用一种,最好是“期待新代码 - 所以

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 ...

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

expect(page).to have_current_path(root_path)

而不是expect(current_path)...

关于ruby-on-rails - Capybara/Rspec - 有没有办法在单击提交之前测试输入框是否已填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61448923/

相关文章:

ruby-on-rails - 在 Ruby on Rails 中使用随机字符串作为 id?

ruby-on-rails - 用 Cucumber 测试嵌套模型表单的简单方法?

ruby-on-rails - 在单元测试 Rails 模型中使用 shoulda-matchers 还是 Factory Girl 更好?

ruby-on-rails - 为什么此rspec请求规范不更新模型?

ruby-on-rails - json post 来设计原因 422/不可处理的实体

ruby-on-rails - Twilio 错误,通过 SID 查找 SMS 时找不到资源

ruby-on-rails - Bundler 不允许我安装 gems

ruby-on-rails - 测试打印 Action

ruby-on-rails - Rubocop 和 capybara : detecting forgotten focus: :true

rspec - Capybara/RSpec 'have_css' 匹配器不起作用,但 has_css 起作用