2012-03-02 235 views
3

我從邁克爾·哈特爾書這個測試失敗RSpec的測試應該通過

describe "follower/following counts" do 
    let(:user) { FactoryGirl.create(:user) } 
    let(:other_user) { FactoryGirl.create(:user) } 

    before do 
    sign_in(user) 
    visit root_path 
    user.follow!(other_user) 
    end 
    it { should have_link('0 following', href: following_user_path(user)) } 
    it { should have_link('1 follower', href: followers_user_path(user)) } 
end 

的問題是,這總是失敗

it { should have_link('1 follower', href: followers_user_path(user)) } 

但是當我將其更改爲

it { should have_link('0 follower', href: followers_user_path(user)) } 

測試通過。這裏是我的模型代碼:

User.rb

has_many :relationships, foreign_key: "follower_id", dependent: :destroy 
has_many :reverse_relationships, foreign_key: "followed_id", class_name: "Relationship", dependent: :destroy 
has_many :followed_users, through: :relationships, source: :followed 
has_many :followers, through: :reverse_relationships, source: :follower 

def follow!(other_user) 
    relationships.create!(followed_id: other_user.id) 
end 

Relationship.rb

attr_accessible :followed_id 
belongs_to :follower, class_name: "User" 
belongs_to :followed, class_name: "User" 
validates :follower_id, presence: true 
validates :followed_id, presence: true 

的routes.rb

resources :users do 
    member do 
    get :following, :followers 
    end 
end 
resources :relationships, only: [:create, :destroy] 

回答

6

您需要後訪問你的頁面跟隨用戶:

before do 
    sign_in(user) 
    user.follow!(other_user) 
    visit root_path 
end 

否則該頁面將在用戶被關注前呈現,因此表示「0追隨者」。

+1

that do it ....不知道我錯過了多少,..謝謝 – Trace 2012-03-02 19:21:42