我遇到此错误,我认为这是因为我的页面顶部有一个导航栏,因此rspec正在检测导航栏中的文本。
Failure/Error: expect(page).to have_content(/description|content/)
expected to find text matching /description|content/ in "Portal Register Login Please sign in Email Password Remember me Sign up Forgot your password?"
我应该在我的rspec测试中写什么才能正确测试内容是否存在?
article_spec.rb
it 'has a list of articles' do
article1 = FactoryGirl.build_stubbed(:article)
visit articles_path
expect(page).to have_content(/description/)
end
规格/工厂/ article.rb
FactoryGirl.define do
factory :article do
title "Title 1"
description "Some description"
user
end
end
编辑:我使用javascript在索引页面上的文章列表的标签之间切换。
index.html.erb
<div class = "container">
<h1 align="center">All Post</h1>
<div class = "row">
<div class = "col-md-9">
<div id="tabs">
<ul class="nav nav-tabs">
<li role="presentation" class="active" data-toggle="tab" ><a href="#tab1">Newest</a></li>
<li role="presentation" data-toggle="tab"><a href="#tab2">Frequent</a></li>
<li role="presentation"data-toggle="tab"><a href="#tab3">Votes</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<% @articles.each do |article| %>
<%= render 'article', article: article %>
<% end %>
</div>
<div class="tab-pane" id="tab2">
<% @articles_views.each do |article_views| %>
<%= render 'article', article: article_views %>
<% end %>
</div>
<div class="tab-pane" id="tab3">
<% @articles_votes.each do |article_votes| %>
<%= render 'article', article: article_votes %>
<% end %>
</div>
</div>
</div>
<div class = "col-md-3"></div>
</div>
</div>
<script>
$(document).ready(function(){
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
});
</script>
_article.html.erb
<h3><%= link_to article.title, article_path(article) %></h3>
答案 0 :(得分:0)
您看到html未经过身份验证。根据您的身份验证系统(如设计),您需要模拟身份验证(https://github.com/plataformatec/devise/wiki/How-To:-Stub-authentication-in-controller-specs)。
此外,我用于功能测试的一个非常有用的事情是打开正在呈现的页面(使用https://github.com/mattheworiordan/capybara-screenshot)。这样您就可以看到为什么您希望在页面上看到的文字不存在
答案 1 :(得分:0)
如果您要测试特定网页上是否有某些内容,您可以像这样编写feature
规范:
# spec/features/article_management_spec.rb
require 'rails_helper'
RSpec.feature 'Article management', type: :feature do
given!(:article1) { FactoryGirl.create(:article) }
scenario 'Page has specific content' do
visit articles_path
expect(page).to have_content(/description/)
end
end
如果articles#index
通过调用@articles = Article.all
之类的数据库来加载文章,那么您必须确保articles
表包含测试数据(article1
在您的情况下)在访问路径之前到位。这就是为什么你需要FactoryGirl.create(:article)
而不是build_stubbed
。
FactoryGirl.create
超过build/build_stubbed
。来自FactoryGirl
doc:
# Returns an article instance that's not saved
article = build(:article)
# Returns an object with all defined attributes stubbed out
stub = build_stubbed(:article)
# Returns a saved article instance
article = create(:article)
要注意的一些别名:
feature
实际上只是describe ..., type: :feature
的别名,scenario
的{{1}}和it
的{{1}}别名。< / p>