ruby-on-rails – 如何在factory_girl工厂中包含一个模块?
发布时间:2020-12-16 19:42:49 所属栏目:百科 来源:网络整理
导读:我试图在我所有的工厂中重用一个帮助方法,但是我无法让它工作.这是我的设置: 助手模块(在spec / support / test_helpers.rb中) module Tests module Helpers # not guaranteed to be unique,useful for generating passwords def random_string(length = 20
我试图在我所有的工厂中重用一个帮助方法,但是我无法让它工作.这是我的设置:
助手模块(在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 / factory / users.rb) FactoryGirl.define do factory :user do sequence(:username) { |n| "username-#{n}" } password random_string password_confirmation { |u| u.password } end end 如果我运行测试(使用rake规范),无论何时使用Factory(:user)创建用户,我都会收到以下错误消息: Failure/Error: Factory(:user) ArgumentError: Not registered: random_string 我可以在我的工厂使用random_string做什么? 我已经尝试过以下内容: >在我工厂的每个级别使用包括Tests :: Helpers(在定义之前,在define和factory之间:user和inside factory:user) 我也没有成功阅读以下链接: > Define helper methods in a module 解决方法
只是一个:
module Tests module Helpers # not guaranteed to be unique,useful for generating passwords def self.random_string(length = 20) chars = ['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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |