ruby-on-rails - 使用 Rails 和 Rspec,如何测试数据库未被方法触及

标签 ruby-on-rails database testing rspec

所以我正在为一种方法编写测试,出于性能原因,该方法应该在不使用 SQL 查询的情况下实现它需要实现的目标。我在想我需要知道的是 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

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

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

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

最佳答案

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

关于ruby-on-rails - 使用 Rails 和 Rspec,如何测试数据库未被方法触及,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13416671/

相关文章:

ruby-on-rails - to_json 将单个对象包装在数组中?

ruby-on-rails - 过滤器前的 Rails ActiveAdmin

database - 功能依赖是 DBMS - 关键

unit-testing - 为从中读取的函数填充 os.Stdin

unit-testing - flutter :测试

ruby-on-rails - 测试 Rails Controller : get and post strange behavior

jquery - Rails 3.1 提交表单而不刷新

ruby-on-rails - 奇怪的 "profiling"输出。从 Rails 命令行

mysql - "shuffle"数据库记录表的最佳方法是什么?

mysql - 可包含可定制产品 (RDMS) 的订单的数据库架构