Active model sending validation error twice during rack test.
I have a simple restful rails api set up to feed json responses, I have a model line.rb where i have following validations.
validates :title, :presence => true, :length => {:minimum => 3, :maximum => 40},
:appropriate_title => {:message => "cannot have . and /"}
validates :department, :presence => true
validates :owner, :presence => true
validates :account, :presence => true
validate :unique_inputs
validates :title, :uniqueness => {
:scope => :account,
:message => 'is already taken for this account',
:case_sensitive => false }
In my spec i have following suite
it "with invalid attributes" do
pos开发者_运维百科t"#{url}/#{account.name}.json", :api_key => application.key, :line => {:department => "Survey"}
--some assertions --
body = JSON.parse(last_response.body)
body.should eql({"error"=>{"message"=>"[\"Title can't be blank\", \"Title is too short (minimum is 3 characters)\",]"}})
end
As you can see since i am not supplying the title to the line it should have triggered the validation error and satisfied my assertion, However i am getting the same validation error twice.
{"error"=>{
"message"=>"[\"Title can't be blank\", \"Title is too short (minimum is 3 characters)\", \"Title can't be blank\", \"Title is too short (minimum is 3 characters)\"]"
}}
This is really weird as in development mode i do not get this validation error twice. If you doubt i'm doing something wrong in my controller, following is what i have in my controller
@line = @current_user.lines.new(params[:line])
if @line.save
respond_with(@line)
else
render :json => {:error => {:message => @line.errors.full_messages}}
end
I can't figure out if it is the bug with the rack test or am i doing something wrong.
Have you tried:
validates :department, :presence => true
validates :owner, :presence => true
validates :account, :presence => true
validate :unique_inputs
validates :title, :presence => true,
:length => {:minimum => 3, :maximum => 40},
:appropriate_title => {:message => "cannot have . and /"},
:uniqueness => {
:scope => :account,
:message => 'is already taken for this account',
:case_sensitive => false }
Do you have some associations that could result in double validation?
You could try adding validate => false
e.g.
has_one :account, :validate => false
I'm not totally sure why this happens but sometimes the associations result in running validations twice in the same object. You can try to test it also in the console by having
l = User.last.lines.new(); l.valid?; l.errors
# might return in double errors
l = Line.new(); l.valid?; l.errors
# errors probably just once
精彩评论