ruby-on-rails - 测试方法是否命中数据库

标签 ruby-on-rails ruby ruby-on-rails-4 rspec rspec-rails

我有以下方法,我想确保它不会访问数据库,除非子域发生更改。

class ApplicationController < ActionController::API
  def current_account
    unless @current_account && @current_account.subdomain == request.subdomain
      @current_account = Account.find_by subdomain: request.subdomain
    end
    @current_account
  end
end

如何测试最少的一个?

require 'rails_helper'
RSpec.describe ApplicationController, type: :controller do
  controller do
    def index
    end
  end

  describe 'current_account' do
    before(:each) do
      FactoryGirl.create(:account, subdomain: 'subdomain1')
      FactoryGirl.create(:account, subdomain: 'subdomain2')
      request.host = 'subdomain1.example.com'
    end

    it 'sets the current_account based on the subdomain' do
      get :index
      expect(subject.send(:current_account).subdomain).to eq('subdomain1')
    end

    it 'changes the current_account when subdomain changes' do
      get :index
      request.host = 'subdomain2.example.com'
      get :index
      expect(subject.send(:current_account).subdomain).to eq('subdomain2')
    end

    xit 'does not hit the database if subdomain does not change' do
      get :index
      # expect to hit the db
      get :index
      # expect to not hit the db
    end
  end
end

我尝试过 expect(Account).to receive(:find) 但没有成功。

最佳答案

我通常为此目的安装此 gem:

https://github.com/brigade/db-query-matchers - 用于数据库查询的 RSpec 匹配器

使用示例:

it 'does not make database queries' do
  expect { subject.make_no_queries }.to_not make_database_queries
end

关于ruby-on-rails - 测试方法是否命中数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31880664/

相关文章:

ruby-on-rails - 定义一个方法来捕获类中的a_method[]

ruby - Cookie 数据大小超过 4K - 但其 'only' 1100 字节已加密

postgresql - 将rails应用程序部署到heroku时经常看到PG::InFailedSqlTransaction错误

ruby-on-rails - 如何编辑或覆盖 ActiveAdmin 的页脚?

ruby-on-rails - Ruby 怪异 : x == y && [x, y].uniq == [x, y]

ruby-on-rails - Rspec:如何使用局部变量和参数测试部分渲染?

ruby-on-rails - Mocha 铁路怪异

ruby-on-rails - Rails/WEBrick错误页面转发

ruby - 用 Ruby 中的组名替换分组的正则表达式

ruby-on-rails-4 - Rails 4 升级 JSON::ParseError 旧 session