如何修复:'any_instance'的弃用警告

时间:2016-10-21 08:47:17

标签: ruby-on-rails ruby-on-rails-4 rspec mocking warnings

我的问题

它运行的场景但在我运行测试时在控制台中bin/rspec)我收到此警告:

  

弃用警告:

     

不使用rspec-mocks的旧any_instance语法中的:should而不显式启用语法。使用新的:expect语法或明确启用:should。    来自/home/wakematta/github/example/spec/features/aspec/features/premium_spec.rb:3:in`block(2级)in'。

     

如果您需要更多这些弃用的回溯   确定在哪里进行必要的更改,您可以进行配置   config.raise_errors_for_deprecations!,它会变成   将弃用警告转换为错误,为您提供完整的回溯。

     

1弃用警告总数

我的场景

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  include ExtraContent
end

app/controllers/concerns/extra_content.rb

module ExtraContent
  extend ActiveSupport::Concern

  included do
    helper_method :extra_content?
  end

  def extra_content?
    current_user.premium?
  end
end

app/controllers/concerns/extra_content.rb

module ExtraContent
  extend ActiveSupport::Concern

  included do
    helper_method :extra_content?
  end

  def extra_content?
    current_user.premium?
  end
end

app/views/users/show.html.haml

%h1= @user.name
- if extra_content?
  %span.premium PREMIUM

spec/features/premium_spec.rb

feature 'Premium features' do
  scenario 'premium user can view extra content' do
    ApplicationController.any_instance.stub(:extra_content?).and_return(true)

    visit '/users/1'
    expect(page).to have_content 'PREMIUM'
  end
end

1 个答案:

答案 0 :(得分:2)

改变这个:

<强> spec/features/premium_spec.rb

feature 'Premium features' do
  scenario 'premium user can view extra content' do
    ApplicationController.any_instance.stub(:extra_content?).and_return(true)

    visit '/users/1'
    expect(page).to have_content 'PREMIUM'
  end
end

为此:

<强> spec/features/premium_spec.rb

feature 'Premium features' do
  scenario 'premium user can view extra content' do
    allow_any_instance_of(ApplicationController).to receive(:extra_content?).and_return(true)

    visit '/users/1'
    expect(page).to have_content 'PREMIUM'
  end
end