Sean L
Sean L

Reputation: 827

Setting up associations within Factory Girl - three has_many & belongs_to nested relationships

I looked in the online manual and I am still not sure how to properly set up associations in Factory Girl. I have a Course which has many Levels which has many Steps (Levels belongs to Course and Steps Belongs to Level)

Here is the error I get - It basically passes the whole step rather than just the course_id, level_id, and (step) id.

No route matches {:action=>"show", :controller=>"steps", :course_id=>#<Step id: 1, 
description: "Description for course 1", cell_location: nil, mc_answer: nil, level_id:
nil, created_at: "2013-10-11 16:03:11", updated_at: "2013-10-11 16:03:11", media_type:
nil, video_link: nil, choice_one: nil, choice_two: nil} 

Here are my factories - I believe I need to somehow create the step so its within Level and Course

FactoryGirl.define do
      factory :user do
        sequence(:name)  { |n| "Person #{n}" }
        sequence(:email) { |n| "person_#{n}@example.com" }
        password "foobar"
        password_confirmation "foobar"

        factory :admin do
            admin true
        end
      end

      factory :course do
        sequence(:title) { |n| "Ze Finance Course #{n}" }
        sequence(:description) { |n| "Description for course #{n}" }
      end

      factory :level do
        sequence(:title) { |n| "Ze Finance Level #{n}" }
      end

      factory :step do
        sequence(:description) { |n| "Description for course #{n}" }
      end


end     

Here are the rspec tests:

describe "attempting a step" do
        let(:step) { FactoryGirl.create(:step)}
        before { sign_in user}

        describe "taking a course" do
            before { visit course_level_step_path(step)} <<< here is where it goes wrong

            it "should increment the user step count" do
                expect do
                    click_button "check answer"
                end.to change(user.user_steps, :count).by(1)
            end

            describe "toggling the button" do
                before { click_button "check answer"}
                it {  should have_selector('input', value: 'remove step')}
            end

        end

Upvotes: 1

Views: 280

Answers (1)

jeanaux
jeanaux

Reputation: 713

You can define associations like this:

factory :step do
  level
  sequence(:description) { |n| "Description for course #{n}" }
end

I'm assuming you have belongs_to :level in your step model?

Also, the error isn't actually a factory girl error. It's a routing error, so how have you defined your routes?

Upvotes: 1

Related Questions