RSpec:避免使用allow任何实例接收

时间:2017-10-18 15:00:14

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

我正在处理一段旧代码。

before do
  allow_any_instance_of(SportRateManager)
    .to receive(:create)
    .and_return(true)
end

有像Rubocop这样的错误:

  

使用' allow_any_instance_of'

避免存根

我读到了RuboCop::RSpec:AnyInstance,我试图像下面一样改变它。

从此

before do
  allow_any_instance_of(SportRateManager)
    .to receive(:create)
    .and_return(true)
end

对此:

let(:sport_manager) { instance_double(SportRateManager) }

before do
  allow(SportRateManager).to receive(:new).and_return(sport_manager)
  allow(sport_manager).to receive(:create).and_return(true)
end

完整背景: - 之前

describe 'POST create' do
    let(:sport_rate) { build(:sport_rate) }
    let(:action) { post :create, sport_rate: sport_rate.attributes }

    context 'when sport rate manager created the rate successfully' do
      before do
        allow_any_instance_of(SportRateManager)
          .to receive(:create)
          .and_return(true)
      end

      it 'returns ok status' do
        action
        expect(response).to have_http_status(:ok)
      end
    end

... - 之后:

describe 'POST create' do
    let(:sport_rate) { build(:sport_rate) }
    let(:action) { post :create, sport_rate: sport_rate.attributes }
    let(:sport_manager) { instance_double(SportRateManager) }

    context 'when sport rate manager created the sport successfully' do
      before do
        allow(SportRateManager).to receive(:new).and_return(sport_manager)
        allow(sport_manager).to receive(:create).and_return(true)
      end

      it 'returns ok status' do
        action
        expect(response).to have_http_status(:ok)
      end
    end

但是这并没有通过错误测试:

#<InstanceDouble(SportRateManager) (anonymous)> received unexpected message :sport_rate with (no args)

1 个答案:

答案 0 :(得分:7)

解决方案差不多完成了。您可能需要在创建

之前添加build :sport_rate

那样的

let(:sport_manager) { instance_double(SportRateManager) }

before do
  allow(SportRateManager).to receive(:new).and_return(sport_manager)
  allow(sport_manager).to receive(:sport_rate).and_return(build :sport_rate)
  allow(sport_manager).to receive(:create).and_return(true)
end