Ruby on rails 如何在Rspec中测试具有多个关联的类方法

Ruby on rails 如何在Rspec中测试具有多个关联的类方法,ruby-on-rails,ruby,testing,rspec,Ruby On Rails,Ruby,Testing,Rspec,我该如何测试类方法。Rspec中的趋势,考虑到它有许多贯穿的关联。趋势分析可行,但目前尚未在Rspec中进行适当审查。有什么建议吗 class Author < ActiveRecord::Base has_many :posts has_many :comments, through: :posts validates :name, presence: true validate :name_length def self.trending hash =

我该如何测试类方法。Rspec中的趋势,考虑到它有许多贯穿的关联。趋势分析可行,但目前尚未在Rspec中进行适当审查。有什么建议吗

class Author < ActiveRecord::Base
  has_many :posts
  has_many :comments, through: :posts

  validates :name, presence: true
  validate :name_length

  def self.trending
    hash = {}
    all.each{|x|
      hash[x.id] = x.comments.where("comments.created_at >= ?", Time.zone.now - 7.days).count
    }
    new_hash = hash.sort_by {|k,v| v}.reverse!.to_h
    new_hash.delete_if {|k, v| v < 1 } 
    new_hash.map do |k,v,|
        self.find(k)      
    end
  end

  private

  def name_length
    unless name.nil?

      if name.length < 2
        errors.add(:name, 'must be longer than 1 character')
      end

    end
  end

end

无论是
FactoryGirl.build
还是
ActiveRecord::Relation#build
都不会将记录持久化到数据库,它们只会返回未保存的对象实例,但
Author.trending
会在数据库中查找记录。您应该对实例调用
save
,将它们持久化到数据库中,或者使用
create
而不是
build

定义“不工作”。另外,我有点困惑,为什么趋势范围在Ruby中做了大量工作?你不能定义你想要的范围吗?这是一些非常可怕的代码,你有一个严重的n+1查询问题。。。
  describe ".trending" do
    it "an instance of Author should be able to return trending" do
      @author = FactoryGirl.build(:author, name:'drew', created_at: Time.now - 11.years, id: 1)
      @post = @author.posts.build(id: 1, body:'hello', subject:'hello agains', created_at: Time.now - 10.years)
      @comment1 = @post.comments.build(id: 1, body: 'this is the body', created_at: Time.now - 9.years)
      @comment2 = @post.comments.build(id: 2, body: 'this was the body', created_at: Time.now - 8.years)
      @comment3 = @post.comments.build(id: 3, body: 'this shall be the body', created_at: Time.now - 7.minutes)
      Author.trending.should include(@comment3)
    end 
  end