【发布时间】:2012-08-23 16:29:07
【问题描述】:
我在编写和测试涉及几个联接和关联的范围时遇到问题。我会尽量保持我的解释简短但尽可能详尽。
我有以下关联:
ExpertTopic > Topic > Articles > Posts
以及以下代码:
class Topic < ActiveRecord::Base
has_many :articles, :order => "position", :dependent => :destroy
has_many :posts, :through => :articles
has_many :expert_topic, :dependent => :delete_all
has_many :experts, :through => :expert_topic
end
还有:
class ExpertTopic < ActiveRecord::Base
belongs_to :topic, :inverse_of => :expert_topic
belongs_to :expert, :inverse_of => :expert_topic
scope :live, joins(:topic => {:articles => :post})
.where("topics.article_count > ? AND posts.live = ?", 0, true)
end
使用ExpertTopic 中的live 范围,我试图缩小与主题相关的专家,其中包含所有实时帖子(通过文章)。
在 Rails 控制台中 ExpertTopic.live.to_sql 是:
"SELECT `experts_topics`.* FROM `experts_topics` INNER JOIN
`topics` ON `topics`.`id` = `experts_topics`.`topic_id` INNER JOIN
`articles` ON `articles`.`topic_id` = `topics`.`id` INNER JOIN
`posts` ON `posts`.`id` = `articles`.`post_id` WHERE
(topics.article_count > 0 AND posts.live = 1)"
我正在使用expert_topic_spec.rb 中的以下代码测试我的范围:
describe ExpertTopic do
before do
@post1 = FactoryGirl.create(:pending_post)
@post2 = FactoryGirl.create(:live_post)
@post3 = FactoryGirl.create(:pending_post)
@post4 = FactoryGirl.create(:live_post)
@non_live_topic = FactoryGirl.create(:topic_with_posts, :posts => [@post1, @post2, @post3])
@live_topic = FactoryGirl.create(:topic_with_posts, :posts => [@post2, @post4])
FactoryGirl.create(:expert_topic, topic_id: @non_live_topic.id)
FactoryGirl.create(:expert_topic, topic_id: @live_topic.id)
end
it 'finds and returns only expert with live topic' do
ExpertTopic.all.count.should == 2
ExpertTopic.live.uniq.count.should == 1
end
end
逻辑是,由于@non_live_topic 至少包含一个未发布的帖子,因此它不被视为实时发布,因此不应通过调用ExpertTopic.live 来返回。但是,最后一个断言失败,因为 ExpertTopic.live.uniq.count 返回 2 而不是 1。
我不知道我的范围是写错了还是我的测试,我真的很感谢有人在调试方面的帮助!
谢谢!
【问题讨论】:
标签: sql ruby-on-rails-3 unit-testing scope associations