我有这个与使用 Mocha 测试模型错误有关的问题:
这是我的控制器(Api / Artist 控制器):
class Api::ArtistsController < ApplicationController respond_to :json def create artist = Artist.new(params[:artist]) if artist.save <-- This is where the test fails render :json=>artist else respond_with artist end end end
这是我的模型(艺术家模型):
class Artist < ActiveRecord::Base include Core::BaseModel attr_accessible :name has_many :albums validates :name, :presence=>true, :uniqueness=>{:case_sensitive=> false} default_scope where :deleted=>false end
这是关于 Artist 控制器的失败测试:
it "should not save a duplicated artist" do Artist.any_instance.stubs(:is_valid?).returns(false) Artist.any_instance.stubs(:errors).returns({:name=>[I18n.t('activerecord.errors.messages.taken')]}) post :create, :format => :json expect(response).not_to be_success expect(response.code).to eq("422") results = JSON.parse(response.body) expect(results).to include({ "errors"=>{ "name"=>[I18n.t('activerecord.errors.messages.taken')] } }) end
当我运行测试时,这是我在上述测试中遇到的错误:
Failure/Error: post :create, :format => :json
NoMethodError:
undefined method `add_on_blank' for {}:Hash
# ./app/controllers/api/artists_controller.rb:17:in `create'
# ./spec/controllers/api/artists_controller_spec.rb:56:in `block (3 levels) in <top (required)>'
我开始使用 Mocha,所以当我想测试重复名称的验证时,我不知道是否有办法测试特定情况下的 json 结果。