【问题标题】:rails test rspec capybara have_css no matchesrails test rspec capybara have_css 没有匹配
【发布时间】:2017-02-20 18:56:59
【问题描述】:

我正在为一个简单的测试而苦苦挣扎

require "rails_helper"

RSpec.feature "Home page", :type => :feature do
 scenario "When a user visit it" do
  visit "/"
  expect(page).to have_css('article', count: 10) 
 end
end

在视图中我有这个代码

<% @articles.each do |article| %>
  <article>
    <header> <%= article.title%> </header>
    <div class="content-summary"> <%= article.body %> </div>
  </article>
  <hr/>
<% end %>

当我运行测试时,我得到了

Failure/Error: expect(page).to have_css('article', count: 10)
   expected to find css "article" 10 times but there were no matches

我运行服务器,我可以看到存在 10 个文章标签。

当我将视图更改为此

<% 10.times do %>
  <article>
    <header> </header>
    <div class="content-summary"> </div>
  </article>
  <hr/>
<% end %>

测试通过

请帮帮我

【问题讨论】:

  • 能否请您出示整个测试文件?
  • @Slava.K 我添加了整个测试文件
  • 您的测试中没有创建任何文章。您需要在 before 块中创建一些。当您运行服务器时,它使用development 数据库,而测试套件使用test one
  • @Slava.K 你是对的。请把它写成接受它的答案:)

标签: ruby-on-rails rspec capybara rspec-rails


【解决方案1】:

Rails 对每个环境都有单独的数据库。本地服务器默认以development 模式运行,因此连接到app_name_development 数据库。然而,RSpec 在test 环境中运行测试并使用app_name_test 数据库。这就是为什么您在运行服务器时看到的文章在 RSpec 测试中不可用。

测试需要手动设置数据。如果您使用的是 RSpec,那么我假设您也安装了 FactoryGirl。在这种情况下,测试应该如下所示:

require "rails_helper"

RSpec.feature "Home page", :type => :feature do
  let!(:articles) { create_list(:article, 10) }

  scenario "When a user visit it" do
    visit "/"
    expect(page).to have_css('article', count: 10) 
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 2017-09-02
    • 2015-01-16
    相关资源
    最近更新 更多