我有以下方法,我想确保它不会访问数据库,除非子域发生更改。
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/