Hommer Smith
Hommer Smith

Reputation: 27852

Invalid record when declaring two Factories in before (:each) in Rspec

I have the following rspec:

require 'spec_helper'

describe KnowledgesController do

  before (:each) do
    @knowledge = FactoryGirl.create(:knowledge)
    @professor = FactoryGirl.create(:professor)
    sign_in @professor
  end

  describe "GET 'show'" do

    it "should be successful" do
      response.should be_success
    end

  end

end

Which when executed gives me the following error:

Failure/Error: @professor = FactoryGirl.create(:professor)
     ActiveRecord::RecordInvalid:
       translation missing: es.activerecord.errors.messages.record_invalid
     # ./spec/controllers/knowledge_controller_spec.rb:7:in `block (2 levels) in <top (required)>'

If I change this:

before (:each) do
        @knowledge = FactoryGirl.create(:knowledge)
        @professor = FactoryGirl.create(:professor)
        sign_in @professor
      end

For:

 before (:each) do
    @professor = FactoryGirl.create(:professor)
    @knowledge = FactoryGirl.create(:knowledge)
    sign_in @professor
 end

I get this error:

Failure/Error: @knowledge = FactoryGirl.create(:knowledge)
     ActiveRecord::RecordInvalid:
       translation missing: es.activerecord.errors.messages.record_invalid

So, I don't think is a matter of the record being invalid, as in one case it hangs on the knowledge and in the other case in the professor.

Do you guys have any thoughts what can be happening?

The factories are these:

#Knowledge

FactoryGirl.define do
  factory :knowledge do |knowledge|
    knowledge.association(:professor)
    knowledge.association(:subject)
    knowledge.association(:level)
  end
end

#Professor

FactoryGirl.define do
    factory :professor do
      first_name 'Mister'
      last_name 'Professor'
      ...
    end
end

Upvotes: 0

Views: 1004

Answers (1)

miguel.camba
miguel.camba

Reputation: 1827

The knowledge class has an associated professor record. Since you are not pasing an explicit professor record to the create method, you are creating a new professor at the same time you creates the knowledge.

One way or another, you are creating two professors with the same attributes. There must be a validation of uniqueness or something like this.

Try this:

before (:each) do
  @professor = FactoryGirl.create(:professor)
  @knowledge = FactoryGirl.create(:knowledge, :professor => @professor)
  sign_in @professor
end

It should work.

Upvotes: 1

Related Questions