Как включить модуль в factory_girl factory?
Я пытаюсь использовать вспомогательный метод на всех моих фабриках, но я не могу заставить его работать. Здесь моя настройка:
Модуль помощника (в 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
A factory (в 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
на каждом уровне моего factory (до define
, между define
и factory :user
и внутри factory :user
)
- в
spec_helper.rb
, у меня уже есть следующее: config.include Tests::Helpers
и он дает мне доступ к random_string
в моих спецификациях
- просто требуется файл в моем factory
Я также прочел следующие ссылки без успеха:
Ответы
Ответ 1
Как насчет простой:
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
Ответ 2
Ответ на apneadiving не работал у меня. Я должен был сделать следующее:
# /spec/support/factory_helpers.rb
module FactoryHelpers
def my_helper_method
# ...
end
end
FactoryGirl::Proxy.send(:include, FactoryHelpers)
Затем вы можете использовать его следующим образом:
FactoryGirl.define do
factory :post do
title { my_helper_method }
end
end
Ответ 3
Вчера я тестировал другие ответы (24.04.2012) и... ни один из них не работает.
Похож, что Factory Девушка gem (v3.2.0) сильно изменилась.
Но я понял быстрое решение:
# factories.rb
module FactoryMacros
def self.create_file(path)
file = File.new(path)
file.rewind
return ActionDispatch::Http::UploadedFile.new(:tempfile => file,
:filename => File.basename(file))
end
end
# also factories.rb
FactoryGirl.define do
factory :thing do |t|
t.file { FactoryMacros::create_file("path-to-file")
end
end