2013-10-03 68 views
2

我想知道第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 

回答

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_與結尾的方法和have_ for有_...?方法。 PARAMS傳遞這樣的:

should be_like(:ruby) 

定製的匹配用於更complecated檢查與自定義成功和失敗消息的能力。 「

+0

」如果您需要將參數傳遞給方法,則同樣的作品。「你能舉一個這樣的例子嗎? – natecraft1

+0

此外,我想知道這個謂詞方法是否需要使用「?」編寫一個方法最後。這個鏈接http://rspec.rubyforge.org/rspec/1.1.11/classes/Spec/Matchers.html說你需要一個自定義匹配器的類嗎? – natecraft1

+0

我已經在答案中添加了一些示例 – faron

相關問題