I have this problem related to testing model errors with Mocha:
This is my controller (Api / Artist controller):
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
This is my model (Artist Model):
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
This is the test where it fails, about Artist controller:
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
When I run the tests, this is the error I get on the above test:
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)>'
I'm starting to use Mocha, so I don't know if there's a way to test the json result for the specific case when I want to test the validation for the duplicated name.