在Rails控制器动作中使用RSpec传递参数给模拟模型方法



我试图模拟一个用户模型的保存方法返回false,并模拟控制器在验证失败的情况下会做什么。

我的规格如下:

require 'spec_helper'
describe UsersController do
  describe 'POST create_email_user' do
    it 'responds with errors json if saving the model fails' do
      @params = {
        :last_name => 'jones',
        :email => 'asdfasdfasfd@'
      }
      User.stub(:new_email_user) .with(@params) .and_return(@mock_user)
      @mock_user.stub(:save) .and_return(false)
      post :create_email_user, :user => @params, :format => :json
      response.body.should == @mock_user.errors.as_json
      response.status.should == :unprocessable_entity
    end
  end
end

控制器动作如下:

class UsersController < ApplicationController
  def create_email_user
    @user = User.new_email_user(params[:user])
    if @user.save
      # code left out for demo purposes
    else
      render json: @user.errors, status: :unprocessable_entity
    end
  end
end

当运行这个规范时,我得到一个错误,基本上说预期的对new_email_user的调用得到了错误的参数:

  1) UsersController POST create_email_user responds with errors json if saving the model fails
     Failure/Error: post :create_email_user, :user => @params, :format => :json
       <User(id: integer, email: string, encrypted_password: string, reset_password_token: string, reset_password_sent_at: datetime, remember_created_at: datetime, sign_in_count: integer, current_sign_in_at: datetime, last_sign_in_at: datetime, current_sign_in_ip: string, last_sign_in_ip: string, created_at: datetime, updated_at: datetime, uid: string, provider: string, first_name: string, last_name: string, registration_id: integer, gender: string, authentication_token: string) (class)> received :new_email_user with unexpected arguments
         expected: ({:last_name=>"jones", :email=>"asdfasdfasfd@"})
              got: (["last_name", "jones"], ["email", "asdfasdfasfd@"])
        Please stub a default value first if message might be received with other args as well. 

似乎rails将具有转换为键值对数组,而我的代码只是在设置中使用直接哈希。

我如何模拟这个转换为数组,或者我做错了吗?

删除用户的.with存根,因为它与测试无关,并且会引起问题。

如果没有.with,存根将为任何参数返回该值。所以:

User.stub(:new_email_user).and_return(@mock_user)

我将有一个单独的规范来确保:

User.should_receive(:new_email_user).with(@params)

并在自己的狭窄范围内诊断问题

相关内容

  • 没有找到相关文章

最新更新