在Factory Girl中建立联想 - 三个has_many& belongs_to嵌套关系

时间:2013-10-11 16:29:43

标签: ruby-on-rails rspec factory-bot

我查看了在线手册,我仍然不确定如何在Factory Girl中正确设置关联。我有一个课程,有很多级别,有很多步骤(级别属于课程,步骤属于级别)

这是我得到的错误 - 它基本上传递了整个步骤而不仅仅是course_id,level_id和(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} 

这是我的工厂 - 我相信我需要以某种方式创建步骤,以便它在Level和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     

以下是rspec测试:

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

1 个答案:

答案 0 :(得分:1)

您可以定义如下关联:

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

我假设你的步模型中有belongs_to :level

此外,错误实际上不是工厂女孩的错误。这是路由错误,那么您如何定义路由?