Using Rails and Rspec, how do you test that the database is not touched by a method

Posted by Will Tomlins on Stack Overflow See other posts from Stack Overflow or by Will Tomlins
Published on 2012-11-16T12:33:45Z Indexed on 2012/11/19 11:05 UTC
Read the original article Hit count: 217

Filed under:
|
|
|

So I'm writing a test for a method which for performance reasons should achieve what it needs to achieve without using SQL queries. I'm thinking all I need to know is what to stub:

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

EDIT: to provide a more specific example:

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

So the test should fail in this example, because the rails 'find_all_by' method relies on SQL.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about database