gpt4 book ai didi

ruby-on-rails - 如何在 factory_girl 工厂中包含模块?

转载 作者:行者123 更新时间:2023-12-03 20:24:03 25 4
gpt4 key购买 nike

我试图在我所有的工厂中重用一个辅助方法,但是我无法让它工作。这是我的设置:

辅助模块(在 spec/support/test_helpers.rb 中)

module Tests
module Helpers
# not guaranteed to be unique, useful for generating passwords
def random_string(length = 20)
chars = ['A'..'Z', 'a'..'z', '0'..'9'].map{|r|r.to_a}.flatten
(0...length).map{ chars[rand(chars.size)] }.join
end
end
end

工厂(在 spec/factories/users.rb 中)
FactoryGirl.define do
factory :user do
sequence(:username) { |n| "username-#{n}" }
password random_string
password_confirmation { |u| u.password }
end
end

如果我运行测试(使用 rake spec ),无论我使用 Factory(:user) 创建用户时都会收到以下错误:
 Failure/Error: Factory(:user)
ArgumentError:
Not registered: random_string

我必须做什么才能使用 random_string在我的工厂里?

我尝试了以下方法:
  • 使用 include Tests::Helpers在我工厂的各个层面(在 define 之前,definefactory :user 之间以及 factory :user 内部)
  • spec_helper.rb ,我已经有以下内容:config.include Tests::Helpers它让我可以访问 random_string在我的规范中
  • 只需要我工厂的文件

  • 我还没有成功阅读以下链接:
  • Define helper methods in a module
  • Different ways of code reuse in RSpec
  • 最佳答案

    仅仅是:

    module Tests
    module Helpers
    # not guaranteed to be unique, useful for generating passwords
    def self.random_string(length = 20)
    chars = ['A'..'Z', 'a'..'z', '0'..'9'].map{|r|r.to_a}.flatten
    (0...length).map{ chars[rand(chars.size)] }.join
    end
    end
    end

    然后:
    FactoryGirl.define do
    factory :user do
    sequence(:username) { |n| "username-#{n}" }
    password Tests::Helpers.random_string
    password_confirmation { |u| u.password }
    end
    end

    好的,明白了:) 执行以下操作:
    module FactoryGirl
    class DefinitionProxy
    def random_string
    #your code here
    end
    end
    end

    关于ruby-on-rails - 如何在 factory_girl 工厂中包含模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7907737/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com