-1

我的一项 Rails 测试遇到了问题。以下是失败但大喊不是的测试。

setup do
  @answer = Answer.new(:title => 'Title', :body => 'Body', :email => 'you@me.com', :quiz_id => 1, :user_id => 1)
end

test 'should not save answer with missing email' do
  @answer.email = nil
  assert !@answer.save, 'answer was saved'
end

我正在检查以确保保存失败 !@answer.save 但这不起作用结果是一个错误的测试,并出现以下错误。

ActiveRecord::StatementInvalid: Mysql2::Error: Column 'email' cannot be null:

我希望我的测试在缺少电子邮件时不保存。非常感谢您的任何帮助。

4

1 回答 1

1

The email column in your MySQL table has been set to not allow null values.

The migration to create the answers table will have something like t.string :email, :null => false.

You will need to create a validation to stop the model from trying to save and triggering the MySQL error.

Try,

validates_presence_of :email

This will stop the model from saving and give you an Active Record validation error message instead.

EDIT:

You will need the validation if you cannot guarantee there will always be an email value. If you can guarantee there will always be an email value, your test on the model is unnecessary because you can guarantee this scenario will never happen.

You may want to test the code that calls this code to ensure it always supplies an email value to the Answer.new method.

于 2013-03-24T14:52:37.143 回答