ruby-on-rails - 使用 capybara 和 rspec 删除测试失败

标签 ruby-on-rails rspec capybara

我正在尝试使用 capybara 和 rspec 测试一篇文章的销毁操作。在 View 文件中,我包含删除链接的警报和 这是我的规范文件:

# spec/features/article_view_spec.rb
require 'rails_helper'

describe 'the article view', type: :feature do

  let(:article) do
    Article.create(title: 'a title', body: 'This is a sample body for a sample article.')
  end

  before(:each) do
    article.reload
    visit root_path
  end
  .
  .
  .
  it 'deletes an article', js: true do
    visit article_path(article)
    find(:xpath, '//link[@href="/articles/1"]').click
    sleep 1.seconds
    alert = page.driver.browser.switch_to.alert
    expect { alert.accept }.to change(Article, :count).by(-1)
  end

但它返回此错误:

Failures:

  1) the article view deletes an article
     Failure/Error: @article = Article.find(params[:id])

     ActiveRecord::RecordNotFound:
       Couldn't find Article with 'id'=1
     # ./app/controllers/articles_controller.rb:9:in `show'
     # ------------------
     # --- Caused by: ---
     # Capybara::ElementNotFound:
     #   Unable to find xpath "//link[@href=\"/articles/1\"]"
     #   ./spec/features/article_view_spec.rb:40:in `block (2 levels) in <top (required)>'

Finished in 4.68 seconds (files took 1.83 seconds to load)
5 examples, 1 failure

Failed examples:

rspec ./spec/features/article_view_spec.rb:38 # the article view deletes an article

顺便说一句,我使用 selenium-webdriver。有什么问题?

最佳答案

由于这是一个 JS 测试并且在模型的显示页面上失败,因此很可能您尚未配置截断模式并且仍在使用事务模式。事务模式不适用于使用除机架测试驱动程序之外的任何内容的测试,因为每个线程都有自己的数据库连接,该连接不知道其他线程连接中缓存的事务。请参阅 - https://github.com/DatabaseCleaner/database_cleaner#rspec-with-capybara-example

其次,让我们重写测试以使用 Capybaras 模式 API 并单击链接,而不是不必要的 xpath,以使其更易于阅读和理解

it 'deletes an article', js: true do
  visit article_path(article)
  expect {
   accept_alert do
    click_link('', href: "/articles/1").click
   end
   sleep 1 #needed because click_link doesn't wait for side effects to occur, although it should really be an expectation to see something that changes on the page after the article is deleted
  }.to change(Article, :count).by(-1)
end

关于ruby-on-rails - 使用 capybara 和 rspec 删除测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35003086/

相关文章:

ruby-on-rails - Association on rails 3 的问题

ruby-on-rails - 从 Rails 应用程序运行 shell 脚本,无论最终用户如何,它都能正常工作吗?

ruby-on-rails - Rails 3 - 文件名太长错误

ruby-on-rails - 如何模拟对 open-uri 的调用

ruby - Rspec any_instance stub 导致错误未定义方法 __rspec_original_dup

ruby - 面对这个问题@driver.quit 在之后给出错误(:context ) in rspec

ruby - 如何检查 Capybara 页面中是否存在 url/链接?

ruby - 如何使用 capybara 和 poltergeist 检索 innertext?

mysql - 重构 Rails 连接表 – 我应该保留哪种格式

ruby-on-rails-3 - 使用 simple_form Rails 时测试 HTML 5 表单验证