RSpec any_instance 弃用:如何解决? [英] RSpec any_instance deprecation: how to fix it?

查看:34
本文介绍了RSpec any_instance 弃用:如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my Rails project I'm using rspec-mocks using any_instance but I want to avoid this deprecation message:

不推荐使用 rspec-mocks 旧的 :should 语法中的 any_instance 而不显式启用该语法.使用新的 :expect 语法或显式启用 :should .

这是我的规格:

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 语法,但我找不到如何正确使用它.

I'd like to use the new :expect syntax but I can't find how to use it properly.

我使用的是 RSpec 3.0.2.

I'm using RSpec 3.0.2.

推荐答案

使用 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

这篇关于RSpec any_instance 弃用:如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆