2012-06-05 16 views
2

我正在編寫一個請求規格,以測試will_paginate工作正常,而且我遇到了一些問題。首先,這裏是我的規格的修剪版本:Rspec在測試分頁時給出假陰性

require 'spec_helper' 

describe "Articles" do 

    subject { page } 

    describe "index page" do 

    let(:user) { FactoryGirl.create(:user) } 

    before { visit news_path } 

    describe "pagination" do 

     before(:all) { 31.times { FactoryGirl.create(:article, user: user) } } 
     after(:all) { Article.delete_all; User.delete_all } 

     let(:first_page) { Article.paginate(page: 1) } 
     let(:second_page) { Article.paginate(page: 2) } 

     it "should not list the second page of articles" do 
     second_page.each do |article| 
      page.should_not have_selector('li', text: article.title) 
     end 
     end 
    end 
    end 
end 

正如你可以看到有一個測試,以確保當用戶訪問該文章的索引頁的文章第二頁沒有顯示。此測試失敗:

1) Articles index page pagination should not list the second page of articles 
    Failure/Error: page.should_not have_selector('li', text: article.title) 
    expected css "li" with text "Article number 1" not to return anything 

我不明白爲什麼這是失敗。當我在開發環境中手動創建31篇文章並在瀏覽器中查看時,分頁工作正常,但是當切換到測試環境時,規格失敗。

文章型號:

class Article < ActiveRecord::Base 
    attr_accessible :body, :title 
    belongs_to :user 

    validates :user_id, presence: true 

    default_scope order: 'created_at DESC' 
end 

用品廠是這樣的:

FactoryGirl.define do 
    factory :article do 
    sequence(:title) { |n| "Article number #{n}" } 
    body "This is the body" 
    user 
    end 
end 
+0

PS - news_path映射到文章的索引 – stephenmurdoch

+0

我懷疑你的工廠創建同樣的文章一次又一次,你添加了一個序列? – apneadiving

+0

我將我的工廠添加到代碼中,我不認爲這是造成問題的原因。 – stephenmurdoch

回答

4

相當令人難以置信,解決,這是做到以下幾點;

變化:

before(:all) { 31.times { FactoryGirl.create(:article, user: user) } } 

到:

before do 
    31.times { FactoryGirl.create(:article, user: user) } 
    visit news_path 
end 

兩件事情我在這裏學到:

  1. before塊不能針對(:all),否則測試失敗
  2. 我需要後塊之前明確地運行visit news_path內,工廠的建立,否則水豚的頁面對象不會是什麼,我希望它是

所以,來說明:

這是行不通的:

# fails because it targets (:all) 
before(:all) do 
    31.times { FactoryGirl.create(:article, user: user) } 
    visit news_path 
end 

,所以並不會有這樣的:

# fails because we are visiting the news path before the objects exist 
before do 
    visit news_path 
    31.times { FactoryGirl.create(:article, user: user) } 
end 

它需要是這樣的:

# not targeting (:all) and only visiting news path after creation of the objects 
before do 
    31.times { FactoryGirl.create(:article, user: user) } 
    visit news_path 
end 

超過20個小時,算出這個,至少我學到了一些新東西等