【问题标题】:Rspec method 'be_following' from Michael Hartl's RoR tutorial chapter 11 Following USersMichael Hartl 的 RoR 教程第 11 章中的 Rspec 方法“be_following”关注用户
【发布时间】:2013-10-09 18:55:32
【问题描述】:

我想知道第 11 章中的这个方法“be_following”是从哪里来的?这是来自 user_spec 的 sn-p:

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 时)生成的方法。是这样吗?以及为什么在这种情况下甚至没有在模型中定义的方法 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

【问题讨论】:

    标签: ruby-on-rails methods rspec model


    【解决方案1】:

    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)
    

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

    【讨论】:

    • "如果您需要将参数传递给方法,则同样有效。"你能举个例子吗?
    • 另外,我想知道这个谓词方法是否只需要编写一个带有“?”的方法。在末尾。这个链接rspec.rubyforge.org/rspec/1.1.11/classes/Spec/Matchers.html 说你需要一个自定义匹配器的类?
    • 我在答案中添加了一些示例
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多