Rspec方法' be_following'来自Michael Hartl的RoR教程第11章跟随用户

时间:2013-10-03 07:15:19

标签: ruby-on-rails methods rspec model

我想知道这个方法来自第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中你是否可以在定义模型关系时使用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

1 个答案:

答案 0 :(得分:3)

RSpec具有内置动态匹配器,用于'?'的方法在末尾。

例如:如果对象响应以下内容?然后你就可以编写像

这样的测试了
it {object.should be_following}

如果您需要将参数传递给方法,则同样有效。

文档:https://www.relishapp.com/rspec/rspec-expectations/v/2-0/docs/matchers/predicate-matchers

更多例子:

class A
  def has_anything?; true end
  def has_smth?(a); !a.nil?  end
  def nice?; true end
  def as_nice_as?(x); x == :unicorn end
end

describe A do
  it {should have_anything}
  it {should have_smth(42)}
  it {should be_nice}
  it {should be_as_nice_as(:unicorn)}
  it {should_not be_as_nice_as(:crocodile)}
end

对于任何以'?'结尾的方法,be_,be_a_,be_an_和has_ for has _...?方法。 参数传递如下:

should be_like(:ruby)

自定义匹配器用于更复杂的检查,能够自定义成功和失败消息。