【问题标题】:RSpec any_instance deprecation: how to fix it?RSpec any_instance 弃用:如何解决?
【发布时间】:2014-08-27 00:39:03
【问题描述】:

在我的 Rails 项目中,我使用 rspec-mocks 并使用 any_instance,但我想避免此弃用消息:

Using any_instance from rspec-mocks' old :should syntax without explicitly enabling the syntax is deprecated. Use the new :expect syntax or explicitly enable :should instead.

这是我的规格:

describe (".create") do
  it 'should return error when...' do
    User.any_instance.stub(:save).and_return(false)
    post :create, user: {name: "foo", surname: "bar"}, format: :json
    expect(response.status).to eq(422)
  end
end

这是我的控制器:

def create
    @user = User.create(user_params)
    if @user.save
      render json: @user, status: :created, location: @user
    else
      render json: @user.errors, status: :unprocessable_entity
    end
end

我想使用 新的 :expect 语法,但我不知道如何正确使用它。

我正在使用 RSpec 3.0.2。

【问题讨论】:

  • 你的 Rspec 版本是多少?

标签: ruby-on-rails ruby testing rspec


【解决方案1】:

使用allow_any_instance_of:

describe (".create") do
  it 'returns error when...' do
    allow_any_instance_of(User).to receive(:save).and_return(false)
    post :create, user: {name: "foo", surname: "bar"}, format: :json
    expect(response.status).to eq(422)
  end
end

【讨论】:

  • 完美运行!
  • 现在allow_any_instance_of 也是marked as deprecated。还有其他解决方案吗?
  • @AlexisWilke - 据我了解 - 它现在被认为是一种设计味道 - 您应该以不需要存根“任何实例”的方式设计服务,但要努力改为存根特定实例...
【解决方案2】:

我可以重现它:

在我的 test.rb 文件中:-

#!/usr/bin/env ruby

class Foo
  def baz
    11
  end
end

在我的 test_spec.rb 文件中

require_relative "../test.rb"

describe Foo do
  it "invokes #baz" do
    Foo.any_instance.stub(:baz).and_return(20)
    expect(subject.baz).to eq(20)
  end
end

现在如果我运行它:-

arup@linux-wzza:~/Ruby> rspec
.

Deprecation Warnings:

Using `any_instance` from rspec-mocks' old `:should` syntax without explicitly enabling the syntax is deprecated. Use the new `:expect` syntax or explicitly enable `:should` instead. Called from /home/arup/Ruby/spec/test_spec.rb:4:in `block (2 levels) in <top (required)>'.

现在,我找到了changelog

allow(Klass.any_instance) 和 expect(Klass.any_instance) 现在打印一个警告。这通常是一个错误,用户通常想要allow_any_instance_of 或expect_any_instance_of。 (萨姆·菲彭)

我把test_spec.rb改成如下:

require_relative "../test.rb"

describe Foo do
  it "invokes #baz" do
    expect_any_instance_of(Foo).to receive(:baz).and_return(20)
    expect(subject.baz).to eq(20)
  end
end

而且效果很好:-

arup@linux-wzza:~/Ruby> rspec
.

Finished in 0.01652 seconds (files took 0.74285 seconds to load)
1 example, 0 failures
arup@linux-wzza:~/Ruby>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 2014-06-26
    • 2020-04-07
    相关资源
    最近更新 更多