失败的rspec测试应该通过

时间:2012-03-02 18:48:24

标签: ruby-on-rails capybara rspec2

我从迈克尔哈特书中得到了这个测试

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]

1 个答案:

答案 0 :(得分:6)

您需要在跟随用户后访问页面

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

否则页面将在用户被关注之前呈现,因此表示“0粉丝”。