ruby-on-rails - 来自 Michael Hartl 的 RoR 教程第 11 章关注用户的 Rspec 方法 'be_following'

标签 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 中是否可以使用定义模型关系(例如 has_many 和 Belongs_to)时生成的 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

最佳答案

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_ 代表 has_...?方法。 参数传递方式如下:

should be_like(:ruby)

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

关于ruby-on-rails - 来自 Michael Hartl 的 RoR 教程第 11 章关注用户的 Rspec 方法 'be_following',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19153044/

相关文章:

ruby - if + else 和 if -> unless 不一致

ruby - 为什么在 RSpec 中弃用了负面的特定异常期望?

ruby-on-rails - 使用 Rspec 测试 Sidekiq worker

ruby-on-rails - 赫罗库:! [rejected] master -> master(非快进)

ruby-on-rails - 使用带突出显示的正则表达式

swift - Swift 中的属性闭包和方法有什么区别?

methods - 重命名类型后,我无法访问其某些方法

ruby-on-rails - 合并两个 ruby 对象

ruby-on-rails - 是否可以扩展 Redcarpet 以从链接自动嵌入 youtube 视频?

java - Box 类,getFull() 方法不会显示准确的 boolean 结果