使用rspec验证模型时测试错误消息

时间:2015-07-30 16:36:54

标签: ruby-on-rails rspec error-handling

我继承了一个rails api,我试图测试控制器。我有一个端点' / api / v1 / vitcords'在哪里我创造新的vitcords。视频模型只有一个验证名称。所以我怀疑的是如何测试当我创建一个没有指定名称的新视频时,我得到了我想要的消息错误,在这种情况下是"必须指定Vitcord名称"。谢谢。

这是Vcord模型

class Vcord
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Spacial::Document
  include Concerns::Vitcord::M3u8
  include Concerns::Vitcord::User

  # Validations
  validates_presence_of     :name

  # Atributes
  field :name,                type: String
  field :location,            type: Array, spacial: true
  field :address,             type: String
  field :closed,              type: Boolean, default: false
  field :public,              type: Boolean, default: false
  field :thumb,               type: String

end

这是控制器video_controller.rb

module Api::V1
  class VitcordsController < ApiController
    def create
      user = current_resource_owner

      # Validation
      param! :name, String, required: true
      param! :location, Hash, required: false
      param! :address, String, required: false

      ap params[:location]
      ap params[:location][:latitude]
      ap params[:location][:longitude]

      # Creating
      vcord = Vcord.new()
      vcord.name = params[:name] if params[:name]
      if params[:location] && params[:location]['latitude'] && params[:location]['longitude']
        vcord.location = {
          lng: params[:location]['longitude'],
          lat: params[:location]['latitude']
        }
      end
      vcord.address = params[:address] if params[:address]
      vcord.creator = user
      if vcord.save
        vcord.members.each do |member|
         Notification.generate_notification_for_vitcord_invited(vcord, member)
      end
      @vitcord = vcord
      else
        error(:internal_server_error, ["Vitcord name has to be specified"], nil)
      end
  end
end

这是规范

require 'rails_helper'

describe "POST /api/v1/vitcords" do
  before(:each) do
    db_drop

    post "/oauth/token", {
     :grant_type => 'assertion', 
     :assertion => TOKEN
    }

    @token = response_json['access_token']
  end

  it "sends an error if a vitcord is created with name nil" do
    header 'Authorization', "Bearer #{@token}"
    post '/api/v1/vitcords', {  
      address: "Calle Rue del Percebe", 
      location: {
        latitude: 40.7127837,
        longitude: -74.00594130000002
      }
     }

     //This does not work but it would be something like this
     expect(error).to eq("Name has to be specified")
   end
end

1 个答案:

答案 0 :(得分:0)

好吧,你应该重构你的代码,但回答你的问题,你可以通过做一个错误给你的对象添加(看看我使用的是@vcord而不是vcord):

@vcord.errors.add(:name, 'Vitcord name has to be specified')

(正如你在这里看到的http://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-add) 在你的考试中:

expect(assigns(:vcord).errors.name).to eq('Vitcord name has to be specified').