0
如何測試Rspec中的類方法.trending考慮到它具有很多直通關聯。但是它目前還沒有在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
測試我試圖使用(沒有工作)
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
定義「不起作用」。另外,我有點困惑,爲什麼趨勢範圍在Ruby中做了一堆工作?你不能只是定義範圍是你想要的? – 2014-09-26 19:53:05
這就是一些非常可怕的代碼,你有嚴重的n + 1查詢問題... – max 2014-09-26 20:11:23