我在编写和测试涉及几个联接和关联的范围时遇到了麻烦。我会尽量保持我的解释简短但尽可能彻底。
我有以下关联:
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
在 中的live
范围内ExpertTopic
,我试图缩小到与主题相关的那些专家,其中包含所有实时帖子(通过文章)。
在 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
.
我不知道我的范围是写错了还是我的测试,我真的很感谢有人在调试方面的帮助!
谢谢!