我如何在Rspec中测试类方法.trending,考虑到它有很多通过关联。 .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
答案 0 :(得分:0)
FactoryGirl.build
和ActiveRecord::Relation#build
都不会将记录持久存储到数据库中 - 它们只返回未保存的对象实例 - 但Author.trending
正在数据库中查找记录。您应该在实例上调用save
以将其保留到数据库,或使用create
代替build
。