Rails测试RSPEC Capybara没有匹配



我在一个简单的测试中挣扎

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

测试通行证

请帮助我

导轨都为每个环境都有单独的数据库。本地服务器默认情况下以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

最新更新