2011-12-21 56 views
0

使用ruby(1.8.7),rails(2.3.8),rspec(1.3.1)rspec-rails(1.3.3)如何测试一个充满复杂SQL查询的方法?有没有办法利用存根和嘲笑。例如,像一个方法:Rspec - 我们应该使用灯具来测试数据库查询吗?

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子句,这是更多的“数据库管理系统”方面谈的了,我怎么写Rspec的测试,将嘲笑这个查询?或者我们应该使用灯具?

回答

2

就我个人而言,我会使用灯具(或更确切地说,FactoryGirl)来测试它。既然你真的在测试你的sql /数据库代码,对我来说,看起来很傻,不要在数据库中测试它。除非你有单独的SQL单元测试设置或其他东西(这对我来说看起来像是矫枉过正)(在大多数情况下))

1

我不喜欢这样的意大利面条SQL,因为它变得非常难以测试。我会说,以测试这种最简单的方法是做类似如下:

  1. 添加“桶”来测试数据库
  2. 确保你把其中的一些在美国,这些条件会/会未通过
  3. 测试结果,并确保你没有得到你想要的东西,并没有得到你做了什么不

这是我会怎么做,反正。

希望这会有所帮助!

相关问题