rails 测试 rspec 水豚 have_css 匹配后

rails test rspec capybara have_css no matches

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

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

测试通过

请帮帮我

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