0

我使用以下内容为 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 多个微博,line 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>
4

2 回答 2

2

我不知道它是否相关,但无论如何我都会发布它,这样它可能会帮助其他人。

您的主页仅显示 30 个提要项目(因为分页),但您的循环检查是否所有提要都存在于您的主页中,而它们不存在,这就是您收到错误的原因...

我对您的问题的解决方案与您的类似,使用分页而不是范围

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
于 2013-04-20T12:45:20.230 回答
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

但是,我不知道这是修复它的最佳方法。

于 2012-11-09T18:57:32.933 回答