我想知道第 11 章中的这种方法“be_following”是从哪里来的?这是来自 user_spec 的片段:
describe "following" do
it { should be_following(other_user) }
its(:followed_users) { should include(other_user) }
describe "followed user" do
subject { other_user }
its(:followers) { should include(@user) }
end
end
我不明白这个方法是如何创建的。据我所知,这不是默认的 rspec 或 capybara 方法。我什至不确定在 rspec 中是否可以在定义模型关系(例如 has_many 和 belongs_to 时)使用 rails 生成的方法。是这样吗?以及为什么在这种情况下甚至没有在模型中定义的方法 be_following 。这是用户模型:
has_many :years
has_many :relationships, dependent: :destroy, foreign_key: :follower_id
has_many :followed_users, through: :relationships, source: :followed
has_many :reverse_relationships, foreign_key: "followed_id",
class_name: "Relationship",
dependent: :destroy
has_many :followers, through: :reverse_relationships, source: :follower
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.encrypt(token)
Digest::SHA1.hexdigest(token.to_s)
end
def following?(followed)
relationships.find_by_followed_id(followed)
end
def follow!(followed)
relationships.create!(:followed_id => followed.id)
end
def unfollow!(other_user)
relationships.find_by(followed_id: other_user.id).destroy!
end