【问题标题】:FactoryGirl Rails: how to properly define AliasesFactoryGirl Rails:如何正确定义别名
【发布时间】:2016-06-24 06:56:08
【问题描述】:

我正在尝试为现有工厂定义别名,但它给了我一个错误: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

【问题讨论】:

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


    【解决方案1】:

    似乎在指南中Post 模型确实有author 关联。
    帖子使用author 而不是user 更自然。
    所以在指南中Post 确实有author 我认为的方法。

    您可以在 Post 模型中将您的 user 关联编辑为 author

    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 等字段设置原始值

    【讨论】:

      猜你喜欢
      • 2019-04-23
      • 1970-01-01
      • 2018-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      相关资源
      最近更新 更多