【问题标题】:FactoryBot factory for a Poro results in undefined method `build'Poro 的 FactoryBot 工厂导致未定义的方法“构建”
【发布时间】:2020-08-07 13:55:24
【问题描述】:

我有一个简单的Poro,像这样:

class Student
  attr_reader :first_name, :last_name
  def initialize(data)
    @first_name = data[:first_name]
    @last_name = data[:last_name]
  end
end

这样的工厂:

FactoryBot.define do
  factory :student do
    first_name {"test first name"}
    last_name {"test last name"}

    # https://thoughtbot.com/blog/tips-for-using-factory-girl-without-an-orm
    initialize_with { new(attributes) }
  end
end

这样的测试:

describe 'StudentSpec', type: :model do
  let(:student) {build(:student)}
  context 'attributes' do
    it 'respond' do
      expect(student).to respond_to(:first_name, :last_name)
    end
  end
end

但这会导致NoMethodError: undefined method 'build' for ....

基于https://thoughtbot.com/blog/tips-for-using-factory-girl-without-an-orm,听起来这应该可行。想知道我做错了什么?

【问题讨论】:

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


    【解决方案1】:

    也许您在规范文件的顶部缺少require 'rails_helper'? 你也试过加FactoryBot吗?

    let(:student) { FactoryBot.build(:student) }
    

    【讨论】:

    • 这是缺少的require 'rails_helper'。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 1970-01-01
    相关资源
    最近更新 更多