与FactoryGirl的关联抛出未定义的方法

时间:2013-10-28 12:18:51

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

我有一项属于许多活动的活动。每当我用rSpec测试我的工厂时,我都会收到错误。

我的测试是:

it "has valid factory" do
    expect(FactoryGirl.build(:activity)).to be_valid
end

错误给出的是:

  1) Activity has valid factory
     Failure/Error: expect(FactoryGirl.build(:activity)).to be_valid
     NoMethodError:
       undefined method `client=' for #<Activity:0x6cbb800>
     # C:in `object'
     # ./spec/models/activity_spec.rb:5:in `block (2 levels) in <top (required)>

因为我已将association :client添加到活动工厂中,所以就是这样:

FactoryGirl.define do
    factory :activity do
        title "Activity"
        start_date {Date.parse('2013-05-13 12:00:00')}
        end_date {Date.parse('2013-05-13 12:15:00')}
        pictogram_id "1"
        association :client
    end
end

客户端本身也通过了所有测试。使用相同的工厂:( clients.rb

FactoryGirl.define do
    factory :client do
        name "Client name"
        background "#FFFFFF"
        birthdate {15.years.ago}
    end
end

由于它不是测试数据库准备/克隆问题,我正在使用 schema.rb 的相关部分更新帖子

  create_table "activities", force: true do |t|
    t.string   "title"
    t.datetime "start_date"
    t.datetime "end_date"
    t.integer  "pictogram_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "activities", ["pictogram_id"], name: "index_activities_on_pictogram_id"

  create_table "activities_clients", id: false, force: true do |t|
    t.integer "activity_id"
    t.integer "client_id"
  end

  add_index "activities_clients", ["activity_id"], name: "index_activities_clients_on_activity_id"
  add_index "activities_clients", ["client_id"], name: "index_activities_clients_on_client_id"

  create_table "clients", force: true do |t|
    t.string   "name"
    t.string   "avatar"
    t.date     "birthdate"
    t.string   "background"
    t.integer  "group_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

任何想法为什么协会都没有...关联?

1 个答案:

答案 0 :(得分:3)

如果您的测试数据库上没有运行数据库架构更改,通常会发生这种情况。确保你运行&#34; rake db:test:prepare&#34;在最近的移民之后。