小编Wil*_*ins的帖子

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

所以我正在编写一个方法的测试,出于性能原因应该实现它不需要使用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 …
Run Code Online (Sandbox Code Playgroud)

database testing rspec ruby-on-rails

3
推荐指数
1
解决办法
2707
查看次数

标签 统计

database ×1

rspec ×1

ruby-on-rails ×1

testing ×1