【发布时间】:2020-03-19 06:39:19
【问题描述】:
我正在写一个RSpec request spec,它看起来大致像(为简洁起见有些缩短):
describe 'Items', type: :request do
describe 'GET /items' do
before do
allow_any_instance_of(ItemsController).to receive(:current_user).and_return(user)
get '/items'
@parsed_body = JSON.parse(response.body)
end
it 'includes all of the items' do
expect(@parsed_body).to include(item_1)
expect(@parsed_body).to include(item_2)
end
end
end
控制器看起来像:
class ItemsController < ApplicationController
before_action :doorkeeper_authorize!
def index
render(json: current_user.items)
end
end
如您所见,我正在尝试存根门卫的 current_user 方法。
测试当前通过并且控制器按预期工作。我的问题是关于这条线的:
allow_any_instance_of(ItemsController).to receive(:current_user).and_return(user)
我根据How to stub ApplicationController method in request spec 中的答案写了这行代码,它有效。但是,the RSpec docs call it a "code smell" 和 rubocop-rspec 抱怨“RSpec/AnyInstance: Avoid stubbing using allow_any_instance_of”。
另一种方法是获取对控制器的引用并使用instance_double(),但我不确定如何从请求规范中获取对控制器的引用。
我应该如何编写此测试以避免代码异味/遗留测试方法?
【问题讨论】:
标签: ruby-on-rails rspec doorkeeper