0

我有以下测试:

    test "should get create" do
   sign_in(FactoryGirl.create(:user))
    assert_difference('Inquery.count') do
      post :create, FactoryGirl.build(:inquery)
    end
    assert_not_nil assigns(:inquery)
    assert_response :redirect
  end

我不断得到:

 2) Error:
test_should_get_create(InqueriesControllerTest):
ActiveRecord::RecordInvalid: Validation failed: Email has already been taken, License number has already been taken

我不明白为什么我在这个特定的测试中得到这个错误,当我有一个非常相似的测试时:

 test "should get create" do
    sign_in(FactoryGirl.create(:user, admin: true))
    assert_difference('Event.count') do
      post :create, FactoryGirl.build(:event)
    end
    assert_not_nil assigns(:event)
    assert_response :success
  end

这很好。明显的区别是 admin: true 行,但我怀疑这没有效果。

添加:

用户工厂.rb

 factory :user do
   first_name "John"
   last_name "Doe"
   email "example@example.com"
   password "foobar"
   password_confirmation "foobar"
   license_number '12345'
   state 'AZ'
   specialty 'Neurosurgery'
  end
4

1 回答 1

1

User的验证失败,因为您的工厂正在为您的测试设置一个新用户,但您的数据库没有被清除。将您的工厂更改为如下所示,以便每次创建时 email 和 license_number 都是唯一的User

factory :user do
  first_name "John"
  last_name "Doe"
  sequence(:email) { |n| "example#{n}@example.com" }
  password "foobar"
  password_confirmation "foobar"
  sequence(:license_number) { |n| "12345#{n}" }
  state 'AZ'
  specialty 'Neurosurgery'
end
于 2012-08-20T17:10:52.660 回答