使用Rails和Rspec,如何测试方法未触及数据库

Wil*_*ins 3 database testing rspec ruby-on-rails

所以我正在编写一个方法的测试,出于性能原因应该实现它不需要使用SQL查询就能实现的目标.我想我需要知道的是什么是存根:

describe SomeModel do
  describe 'a_getter_method' do
    it 'should not touch the database' do
      thing = SomeModel.create

      something_inside_rails.should_not_receive(:a_method_querying_the_database)

      thing.a_getter_method
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

编辑:提供一个更具体的例子:

class Publication << ActiveRecord::Base
end
class Book << Publication
end
class Magazine << Publication
end

class Student << ActiveRecord::Base
  has_many :publications

  def publications_of_type(type)
    #this is the method I am trying to test.  
    #The test should show that when I do the following, the database is queried.

    self.publications.find_all_by_type(type)
  end
end


describe Student do
  describe "publications_of_type" do
    it 'should not touch the database' do
       Student.create()
       student = Student.first(:include => :publications)
       #the publications relationship is already loaded, so no need to touch the DB

       lambda {
         student.publications_of_type(:magazine)
       }.should_not touch_the_database
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

所以测试应该在这个例子中失败,因为rails的'find_all_by'方法依赖于SQL.

his*_*rat 6

SomeModel.should_not_receive(:connection) 应该这样做.

  • 谢谢你的回答.它可以作为测试,但是当测试失败时,测试会抛出"堆栈级别太深".目前它仍然是一个考验. (3认同)