我有一个简单的restful rails api设置来提供json响应,我有一个模型line.rb,我有以下验证。
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 }
在我的规范中,我有以下套件
it "with invalid attributes" do
post"#{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
正如你所看到的,因为我没有提供该行的标题,它应该触发验证错误并满足我的断言,但是我得到相同的验证错误两次。
{"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)\"]"
}}
这真的很奇怪,因为在开发模式中,我没有两次得到此验证错误。如果你怀疑我在我的控制器中做错了什么,以下是我在控制器中的内容
@line = @current_user.lines.new(params[:line])
if @line.save
respond_with(@line)
else
render :json => {:error => {:message => @line.errors.full_messages}}
end
我无法弄清楚它是机架测试的错误还是我做错了什么。
答案 0 :(得分:1)
你试过了吗?
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 }
答案 1 :(得分:0)
您是否有一些可能导致双重验证的关联?
您可以尝试添加validate => false
,例如
has_one :account, :validate => false
我不完全确定为什么会发生这种情况,但有时这些关联会导致在同一个对象中运行两次验证。您也可以尝试通过
在控制台中测试它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