Factory Girl + Rspec gives following error: Action

2019-08-20 14:55发布

问题:

I defined a Course >> Level >> and Step in factory girl. Step belongs to level and level belongs to course (each of them has a has_many relationship the other way).

Here is the error (I am not even sure where to start):

Failure/Error: before { visit course_level_step_path(course.id, level.id, step.id)}
 ActionView::Template::Error:
   0x003fe5daf528a0 is not id value

Here is my required route:

 course_level_step GET        /courses/:course_id/levels/:level_id/steps/:id(.:format) steps#show

Here my rspec:

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

        describe "taking a course" do
            before { visit course_level_step_path(course.id, level.id, step.id)}  <<< here is the problem

            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

Here are my factories:

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
        course
        sequence(:title) { |n| "Ze Finance Level #{n}" }
      end

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

Any guidance on the error and how to solve it would be much appreciated.

回答1:

Your error seems to be coming from the view. Can you post the code for that and the controller too? Also to save you more trouble later: this line

before { visit course_level_step_path(course.id, level.id, step.id) } 

creates one step, two levels, and three courses because of the way Factory Girl works. You probably want to re-write two of your let clauses to

let(:level) { FactoryGirl.create(:level, course: course) }
let(:step) { FactoryGirl.create(:step, level: level) }