如何为model数据的验证写单元测试

阅读更多
假设我们有一个model类Project,它的字段name是必须是唯一。它的单元测试可以如下:
  def test_project_name_should_be_uniqure
    project = Project.create!(:name => 'my project')
    assert_raises(ActiveRecord::RecordInvalid){
      Project.create!(:name => 'my project')
    }
  end

当然,更好的写法是这样:
  def test_project_name_should_be_uniqure
    project = Project.create!(:name => 'my project')
    another_project = Project.new(:name => 'my project')
    assert !another_project.valid?
    assert_equal ['Name has already been taken'],another_project.errors.full_messages
  end

你可能感兴趣的:(单元测试,ActiveRecord)