2

第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 またはカピバラのメソッドではありません。has_manyやbelongs_toなどのモデル関係を定義するときに、rspecで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
4

1 に答える 1

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_ の have_...? メソッド。パラメータは次のように渡されます。

should be_like(:ruby)

カスタム マッチャーは、成功メッセージと失敗メッセージをカスタマイズする機能を備えた、より複雑なチェックに使用されます。

于 2013-10-03T07:52:38.237 に答える