3

I have this test from michael hartl book

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

the problem is that this always fails

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

but when i change it to

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

the test passes. Here is my model code:

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]

1 Answer 1

6

You need to visit the page after you've followed the user:

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

else the page will have been rendered before the user was followed, and thus says "0 followers".

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.