我试图在我所有的工厂中重用一个帮助方法,但是我无法让它工作.这是我的设置:
助手模块(在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)
>在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','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