如何在Rspec中测试具有has Many Through关联的类方法



考虑到Rspec中有一个具有多个直通关联,我该如何测试类方法。trending。趋势是可行的,但目前还没有在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

我尝试使用的测试(它不起作用)

  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

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

相关内容

最新更新