我使用以下内容为static_pages_spec.rb中的第10章练习1和2编写测试,当我将其他测试通过时,我收到以下错误:
1) Static pages Home page for signed-in users should render the user's feed
Failure/Error: page.should have_selector("li##{item.id}", text: item.content)
expected css "li#1138" with text "Lorem ipsum" to return something
# ./spec/requests/static_pages_spec.rb:25:in `block (5 levels) in <top (required)>'
# ./spec/requests/static_pages_spec.rb:24:in `block (4 levels) in <top (required)>'
显然,一旦FactoryGirl创建超过30个微博,行item.id测试就会以某种方式破坏。
这是static_pages_spec.rb:
describe "Home page" do
before { visit root_path }
it { should have_selector('h1', text: 'Sample App') }
it { should have_selector('title', text: full_title('')) }
describe "for signed-in users" do
let(:user) { FactoryGirl.create(:user) }
before do
31.times { FactoryGirl.create(:micropost, user: user) }
sign_in user
visit root_path
end
after { user.microposts.delete_all }
it "should render the user's feed" do
user.feed.each do |item|
page.should have_selector("li##{item.id}", text: item.content)
end
end
it "should have micropost count and pluralize" do
page.should have_content('31 microposts')
end
it "should paginate after 31" do
page.should have_selector('div.pagination')
end
end
end
这是我的_feed_item.html.erb部分:
<li id="<%= feed_item.id %>">
<%= link_to gravatar_for(feed_item.user), feed_item.user %>
<span class="user">
<%= link_to feed_item.user.name, feed_item.user %>
</span>
<span class="content"><%= feed_item.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(feed_item.created_at) %> ago.
</span>
<% if current_user?(feed_item.user) %>
<%= link_to "delete", feed_item, method: :delete,
data: { confirm: "You sure?" },
title: feed_item.content %>
<% end %>
</li>
答案 0 :(得分:2)
我不知道它是否相关但我会发布它,所以它可能会帮助其他人。
您的主页只显示30个Feed项(由于分页),但是您的循环检查您的主页中是否存在您没有的所有Feed,这就是您遇到错误的原因...
我的问题解决方案与您的问题类似,使用的是paginate而不是range
it "should render the user's feed" do
user.feed.paginate(page: 1).each do |item|
page.should have_selector("li##{item.id}", text: item.content)
end
end
答案 1 :(得分:0)
我通过限制Feed行项目测试来修复此问题,只检查前28个帖子。
it "should render the user's feed" do
user.feed[1..28].each do |item|
page.should have_selector("li##{item.id}", text: item.content)
end
end
但是,我不知道这是解决问题的最佳方法。