Rails 4 使用 Engine 中的 Factory Girl 工厂

Posted

技术标签:

【中文标题】Rails 4 使用 Engine 中的 Factory Girl 工厂【英文标题】:Rails 4 Use Factory Girl factories from Engine 【发布时间】:2014-10-10 03:16:24 【问题描述】:

我创建了一个 rails 引擎(完整的,不可安装的)来为许多不同的 rails 应用程序提供模型。我使用 Factory Girl Rails 来测试这个引擎,引擎本身的测试都运行良好。

我现在希望能够在包含此引擎的其他应用中使用这些工厂。

Gemspec 的依赖项如下所示:

s.add_dependency "rails", "~> 4.0.3"
s.add_dependency "mysql2", "~> 0.3.15"

s.add_development_dependency "rspec-rails", "~> 3.0.0.beta"
s.add_development_dependency "factory_girl_rails", "~> 4.4.1"
s.add_development_dependency "shoulda-matchers", "~> 2.5.0"

我已经在 /spec/factories.rb 中定义了我的工厂:

factory :user do
  ...
end

为了将 factory.rb 添加到 factory girl 的定义路径中,我在 /lib/engine_name/engine.rb 文件中添加了以下内容:

class Engine < ::Rails::Engine

    initializer "model_core.factories", :after => "factory_girl.set_factory_paths" do
      FactoryGirl.definition_file_paths << File.expand_path('../../../spec/factories.rb', __FILE__) if defined?(FactoryGirl)
    end

end

在我的 Rails 应用程序中,我通过将以下内容添加到 Gemfile 来包含引擎:

gem 'engine_name', git: "<GIT_LOCATION>"

我还将 factory_girl_rails 添加到应用程序(有没有办法可以从引擎中公开它?而不是必须在应用程序 Gemfile 中指定它?)。

并且在 spec_helper.rb 中需要工厂女孩导轨:

require 'factory_girl_rails'

现在,当我编写如下控制器测试时:

it "saves the user to the database" do
  expectpost :create, user: attributes_for(:user).to changeUser.count.by(1)
end

我收到错误:“未注册工厂:用户”

我通过打开 ruby​​ 控制台并运行 FactoryGirl.definition_file_paths 仔细检查了工厂女孩定义文件路径,我可以在输出中看到来自引擎的 factory.rb:"/home/ ... / gems/engine-name-abc123/spec/factories.rb"

我还需要做什么才能使这些工厂可用吗?

(我在 *** 上发现了一些类似的问题,除此之外,似乎都指向在 engine.rb 中添加这些行,或者在 factory.rb 中指定命名空间,但我没有在这个引擎中使用命名空间。)

【问题讨论】:

有答案:***.com/questions/20261585/… 【参考方案1】:

我发现最简单的方法是添加一个简单地复制工厂的安装生成器。我还让生成器运行 install migrations rake 任务,因为我在任何使用引擎的应用程序中都需要这些。

所以,在lib/generators/my_engine/install/install_generator.rb

module MyEngine
    module Generators
        class InstallGenerator < Rails::Generators::Base
          source_root File.expand_path('../templates', __FILE__)

          def copy_migrations
            rake("my_engine:install:migrations")
          end

          def copy_factories
            copy_file "../path/to/spec/factories.rb", "spec/factories.rb"
          end

        end
    end
end

现在在使用此引擎的项目中,我只需运行 rails generate my_engine:install,工厂(和迁移)就可以使用了。

【讨论】:

引擎的工厂变了怎么办? 这与您想使用更高版本的 gem 没有什么不同。如果工厂在引擎中更新,依赖于此的客户端只需更新其 gemfile 以指向最新的。

以上是关于Rails 4 使用 Engine 中的 Factory Girl 工厂的主要内容,如果未能解决你的问题,请参考以下文章

Ruby on Rails Mountable vs. Full Engine

Google App Engine 上的 Ruby on Rails 应用程序

Python - Google App Engine - Django 模板中的方法

如何处理 Google App Engine 中的秘密?

Rails 3.1 引擎:my_engine.gemspec、add_dependency、add_development_dependency 和 Gemfile 的区别

将 Ruby on Rails 应用程序部署到 Google App Engine