FactoryGirl Rails:如何正确定义别名

时间:2016-06-23 21:55:33

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

我尝试为现有工厂定义别名,但它给我一个错误:undefined method author= for #<Post:0x7217bc8>

FactoryGirl定义

FactoryGirl.define do

  factory :user, aliases: [:author] do |f|
    f.username { "Banana" }
    f.email { "Ilovebanana" }
  end

  factory :post do |p|
    author
    p.title { "Monkey" }
    p.content { Faker::Lorem.paragraph(2) }
  end
end

这两个模型具有User has_many:posts和Post belongs_to:user

的关联

测试跑:

it "should be valid" do
    post = build(:post)
    post.should be_valid
 end

有什么建议为什么它会给我这个错误?即时关注此guide

1 个答案:

答案 0 :(得分:1)

似乎在指南Post模型中确实有author关联 对于帖子来说,author而不是user更为自然 因此,在指南中Post确实有author方法。

您可以在user模式中将author关联修改为Post,例如

belongs_to :author, class_name: 'User', foreign_key: 'user_id'

或将post工厂更改为此类

factory :post do
  association :user, factory: :author # or user { create :author }
  title   "Monkey"
  content Faker::Lorem.paragraph(2)
end

另请注意,您无需使用块将原始值设置为titlecontent

等字段
相关问题