使用capybara和rspec删除测试失败

时间:2016-01-25 21:51:39

标签: ruby-on-rails rspec capybara

我正试图用capybara和rspec来测试一篇文章的破坏行为。在视图文件中,我包含一个删除链接的警报和 这是我的spec文件:

# 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。有什么问题?

1 个答案:

答案 0 :(得分:1)

由于这是一个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