Noah Clark
Noah Clark

Reputation: 8131

Validations Cause Test To Fail

I have the following test:

    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

and I keep getting:

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

What I don't understand is why I get this error in this particular test, when I have a very similar test:

 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

and this does just fine. The obvious difference is the admin: true line, but that has no effect as I suspected.

Added:

User_factory.rb

 factory :user do
   first_name "John"
   last_name "Doe"
   email "[email protected]"
   password "foobar"
   password_confirmation "foobar"
   license_number '12345'
   state 'AZ'
   specialty 'Neurosurgery'
  end

Upvotes: 0

Views: 41

Answers (1)

girasquid
girasquid

Reputation: 15516

Your User is failing validations because your factory is setting up a new user for your test, but your database isn't being cleared in between. Change your factory to look like this, so that email and license_number are unique each time you create a 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

Upvotes: 1

Related Questions