如何填充测试数据库中的表?

时间:2015-08-31 15:01:36

标签: ruby-on-rails ruby-on-rails-4 rspec rspec2

请帮助解决问题。

模型:

class StatusPoll < ActiveRecord::Base
  has_many :polls
end

class Poll < ActiveRecord::Base
  belongs_to  :status_poll
end

规格/工厂/ status_poll.rb:

FactoryGirl.define do
  factory :status_poll_0 do
    id 0
    title 'open'
  end

  factory :status_poll_1 do
    id 1
    title 'closed'
  end  
end

规格/工厂/ poll.rb:

FactoryGirl.define do
  factory :poll do
    association :status_poll_0
    sequence(:title){ |i| "title#{i}" }
    description Faker::Lorem.paragraph(7)
  end
end

我需要填写表'status_poll'跟随值:

id: 0
title 'open'

id: 1
title: 'closed'

但在控制台中运行规格后,我会收到以下错误消息:

kalinin@kalinin ~/rails/phs $ rspec spec/models/poll_spec.rb
F...

Failures:

  1) Poll has a valid factory
     Failure/Error: expect(FactoryGirl.create(:poll)).to be_valid
     NameError:
       uninitialized constant StatusPoll0

2 个答案:

答案 0 :(得分:1)

uninitialized constant StatusPoll0

您收到此错误,因为您没有任何名为StatusPoll0的类。相反,你有一个名为StatusPoll的类。因此,您必须为工厂指定类。

spec/factories/status_poll.rb中,指定工厂类如下:

FactoryGirl.define do
  factory :status_poll_0, class: 'StatusPoll' do
    id 0
    title 'open'
  end

  factory :status_poll_1, class: 'StatusPoll' do
    id 1
    title 'closed'
  end  
end

这可以解决您的问题。

答案 1 :(得分:1)

我不推荐你正在使用的方法。

相反,创建一个通用status_poll工厂,如下所示:

FactoryGirl.define do
  factory :status_poll do
  end
end

然后在poll工厂中,创建如下特征:

FactoryGirl.define do
  factory :poll do
    sequence(:title){ |i| "title#{i}" }
    description Faker::Lorem.paragraph(7)

    trait :poll_with_status_poll_0 do
      after :build, :create do |poll|
       status_poll = create :status_poll, id: 0, title: "open"
       poll.status_poll = status_poll
      end
    end

    trait :poll_with_status_poll_1 do
      after :build, :create do |poll|
       status_poll = create :status_poll, id: 1, title: "closed"
       poll.status_poll = status_poll
      end
    end
  end
end

现在在您的规范中,您可以构建如下特征:

let(:poll_with_status_poll_0) { create :poll, :poll_with_status_poll_0 }
let(:poll_with_status_poll_1) { create :poll, :poll_with_status_poll_1 }

您真的想尝试对工厂进行建模以镜像您的导轨模型。在您的方法中,您生成的工厂模型不代表您应用中的真实类。