使用ruby(1.8.7)
,rails(2.3.8)
,rspec(1.3.1)
和rspec-rails(1.3.3)
如何测试一个充满复杂SQL查询的方法?有没有办法利用存根和模拟。例如,一种方法:
class Bucket << ActiveRecord::Base
attr_accessor :students
def populate_students_subassesmentwise(subassesment, mentor)
student_ids = Mark.find(:all,
:joins => "#{self.student_current_klass} #{self.current_mentors}",
:conditions => ["marks.subject_id = ? AND st.klass_id = ? AND
IF(sub.is_elective IS TRUE,
(se.student_id = st.id AND se.subject_klass_id = marks.klass_id AND se.student_klass_id = st.klass_id AND marks.subject_id = se.subject_id),
(marks.klass_id = st.klass_id))
AND u.account_enabled IS TRUE AND sub.active IS TRUE AND k.active IS TRUE AND marks.markable_id = ? AND marks.markable_type = ?
AND ROUND(marks_obtained/marks_total*100) BETWEEN ? AND ? ",
mentor.subject_id, mentor.klass_id, subassesment.id, "Subassesment", min_range, max_range],
:group => "marks.id").collect(&:student_id)
self.assign_students(student_ids) # This is a call to another instance method that runs a query to find the students having ids equal to student ids and assign it to the students attr_accessor
end
end
正如您所看到的,有很多JOIN,IF和WHERE子句,更多的是用'DBMS'来讨论,如何在Rspec中编写可以模拟此查询的测试?或者我们应该使用固定装置?
答案 0 :(得分:2)
就我个人而言,我会使用灯具(或者更确切地说,FactoryGirl)进行测试。既然你真的在测试你的sql /数据库代码,那么对我来说,不要在数据库中测试它似乎很愚蠢。除非你有一个单独的sql单元测试设置或某些东西(这对我来说似乎有点过分;)(在大多数情况下))
答案 1 :(得分:1)
我不喜欢像这样的意大利面条SQL,因为它很难测试。我想说最简单的测试方法是做类似以下的事情:
无论如何,我就是这样做的。
希望这有帮助!