RSpec any_instance弃用:如何解决?

Row*_*ish 47 ruby testing rspec ruby-on-rails

在我的Rails项目中,我正在使用任何实例的rspec-mocks,但我想避免这个弃用消息:

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
Run Code Online (Sandbox Code Playgroud)

这是我的控制器:

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
Run Code Online (Sandbox Code Playgroud)

我想使用new:expect语法,但我找不到如何正确使用它.

我正在使用RSpec 3.0.2.

Uri*_*ssi 98

用途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
Run Code Online (Sandbox Code Playgroud)


Aru*_*hit 5

我能够重现它:

在我的test.rb文件中: -

#!/usr/bin/env ruby

class Foo
  def baz
    11
  end
end
Run Code Online (Sandbox Code Playgroud)

在我的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
Run Code Online (Sandbox Code Playgroud)

现在,如果我运行它: -

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)>'.
Run Code Online (Sandbox Code Playgroud)

现在,我找到了更改日志

allow(Klass.any_instance)expect(Klass.any_instance)现在打印一个警告.这通常是一个错误,用户通常需要allow_any_instance_ofexpect_any_instance_of代替.(Sam Phippen)

我改变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
Run Code Online (Sandbox Code Playgroud)

它完美地运作: -

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>
Run Code Online (Sandbox Code Playgroud)