いくつかの結合と関連付けを含むスコープの作成とテストに問題があります。説明は簡潔に、しかしできるだけ徹底的にするように努めます。
私には次の関連があります。
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
ライブではない投稿が少なくとも1つ含まれているため、ライブとは見なされないため、への呼び出しによって返されるべきではないということExpertTopic.live
です。ただし、の代わりにがExpertTopic.live.uniq.count
返されるため、最後のアサーションは失敗します。2
1
スコープが間違って書かれているのか、それとも私のテストなのかはわかりません。デバッグに誰かの助けを借りていただければ幸いです。
ありがとう!