Rails。 Capybara fill_in 找到文本输入但没有 fill_in

Rails. Capybara fill_in finds text inputs but doesn't fill_in

所以我的 Rails 应用程序中有这个功能规范

require 'rails_helper'

feature 'As a signed in user' do
  let(:user) {create(:user)}
  let(:article) { create(:article)}
  before {login_as(user, :scope => :user )}

  scenario 'I can edit article with valid attributes' do
    visit edit_article_path(article)
    puts current_path
    fill_in 'article_name', with: 'Valid name'
    fill_in 'article_content', with: 'Valid content'
    # save_and_open_page
    click_button 'Update Article'
    expect(article.name).to eq 'Valid name'
  end
end

fill_in 实际上并没有用 Valid nameValid content 填充输入字段。我通过保存和打开页面来调试它,并且值保持不变,所以我想这不是我的 Rails 应用程序的问题,而是 Capybara 的问题。在其他未来规范中:

require 'rails_helper'

feature 'As a signed in user' do
  let(:user) {create(:user)}
  let(:article) { build(:article)}
  before {login_as(user, :scope => :user )}

  scenario 'I can create article with valid attributes' do
    visit '/articles/new'
    fill_in 'Name', with: article.name
    fill_in 'article_content', with: article.content
    expect {click_button 'Create Article'}.to change {Article.count}.by(1)
  end
end

一切正常。我得到的错误是:

Failures:

  1) As a signed in user I can edit article with valid attributes
     Failure/Error: expect(article.name).to eq 'Valid name'

       expected: "Valid name"
            got: "Name1"

       (compared using ==)
     # ./spec/features/articles/article_update_spec.rb:15:in `block (2 levels) in <top (required)>'

它可能是什么原因以及如何使规范通过?

看来您正在使用机架测试驱动程序,因为您的测试未标记为 js: true。假设这是真的,您的问题是 article 已经在内存中,并且在检查名称更改之前没有从数据库重新加载。将您的测试更新为以下内容将强制重新加载,然后您的测试应该会通过

expect(article.reload.name).to eq 'Valid name'

如果您不使用机架测试驱动程序,那么 click_button 将是异步的,并且您会遇到其他问题,因为您在检查数据库对象更改之前没有检查浏览器中的更改。