我想知道第11章中的这个方法'be_following'从哪里来?这里是user_spec的片段:Michael Hartl的RoR教程第11章中的Rspec方法'be_following'关注用户
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或水豚方法。我甚至不确定在rspec中是否可以在定义模型关系时使用rails生成的方法,例如has_many和belongs_to。是这样吗?为什么在这种情况下,当模型中甚至没有定义该方法时,该方法就是如此。这里是用户模型:
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
”如果您需要将参数传递给方法,则同样的作品。“你能举一个这样的例子吗? – natecraft1
此外,我想知道这个谓词方法是否需要使用“?”编写一个方法最后。这个链接http://rspec.rubyforge.org/rspec/1.1.11/classes/Spec/Matchers.html说你需要一个自定义匹配器的类吗? – natecraft1
我已经在答案中添加了一些示例 – faron