使用Rspec测试方法是否未命中数据库

时间:2013-04-21 18:33:08

标签: ruby-on-rails ruby-on-rails-3 rspec

我在Rails 3应用程序中编写用于缓存的Rspec测试。我使用Redis作为缓存存储。

我有一个尝试从Redis中提取数据的方法,如果没有找到,将使用该数据库。

有没有办法测试数据库是否未被访问? (所以我确信数据是从Redis中提取的。)

1 个答案:

答案 0 :(得分:1)

如果您正在使用,则可以模拟模型调用以引发错误。这是一个例子:

describe 'when cached' do
  it 'should not hit the database' do
    # first request should add the object to the cache
    get '/users/1'

    # make db calls fail
    expect(User).not_to receive(:find)

    # send the request again
    get '/users/1'
  end
end