在我的Rails项目中,我使用rspec mock来使用任何_实例,但我想避免这种不赞成的消息:

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

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

我用的是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

Ruby-on-rails相关问答推荐

为什么Rails数值验证器不使用规格化值?

Gemfile需要较新版本的依赖项

在URL中将下划线更改为连字符Ruby on Rails

创建大哈希的 Ruby 方法

Turbo-Rails:如何将 Turbo Frame 添加到 `application.html.erb`?

Rails 4.1 Mailer 预览和设计自定义邮箱

Rails cron 与时俱进,设置环境

如何判断是否已经在 ruby​​ on rails 的数据库事务中?

Gem 更新:在从 ASCII-8BIT 到 UTF-8 到 US-ASCII 的转换中,无法将 "\xE7" 转换为 UTF-8

fields_for 表单构建器对象为零

Rails ActiveRecord 查询日期范围

Rails(或 Ruby):Yes/No 而不是 True/False

如何在rails中异步加载部分页面

导轨链接到:远程

表单中的第一个参数不能包含 nil 或为空 - Rails 4

您推荐哪些工具来分析 Rails 应用程序?

Rails 4,Capistrano 3.0.0,无法加载这样的文件 - 部署

如何检测rails是否在根url?

使用设计创建一个用户显示页面

在 Rails 3 中突出显示当前页面的最佳方法? -- 有条件地将css类应用于链接