如何使用Devise和rspec测试Rails3引擎

时间:2011-01-24 13:19:40

标签: ruby-on-rails-3 rspec devise rails-engines

我正在开发一个依赖于Devise Gem的Rails引擎。我的引擎本身也是一个宝石,我需要为那个东西编写测试。为此,我做了很多关于如何从宝石内部测试引擎的读数,我进入了以下设置:

my_engine
 +- app    # my engine stuff
 +- config # my engine stuff
 +- Gemfile
 +- lib    # my engine stuff
 +- public # my engine stuff
 +- spec
     +- controllers    # controller tests
     +- models         # model tests
     +- dummy          # a dummy application that is using the 'my_engine/Gemfile' 
     +- spec_helper.rb # the spec helper that boots the dummy app

在我加入Devise gem之前,我可以编写测试并使用

运行它们
rake spec

现在我有了Devise gem和这样的用户模型

class Manager::User < ActiveRecord::Base
    devise :database_authenticatable, :registerable, # ...
end

我的测试失败指向用户类和设计调用。

`method_missing': undefined method `devise'

所以现在我尝试调查错误并找出如何使用设计和我的引擎一起启动虚拟应用程序。 规范助手看起来像这个

# my_engine/spec/spec_helper.rb#
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../dummy/config/environment.rb",  __FILE__) # boots the dummy app and fails
# more rspec stuff gies here

evnironment.rb

# my_engine/spec/dummy/config/environment.rb
# Load the rails application
require File.expand_path('../application', __FILE__)

# Initialize the rails application
Dummy::Application.initialize!

application.rb

# my_engine/spec/dummy/config/application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(:default, Rails.env) if defined?(Bundler)
# Dummy::Application definition follows here (the common stuff)

boot.rb

# my_engine/spec/dummy/config/boot.rb
require 'rubygems'
# Loads the gemfile from 'my_engine/Gemfile'
gemfile = File.expand_path('../../../../Gemfile', __FILE__)

begin
  ENV['BUNDLE_GEMFILE'] = gemfile
  require 'bundler'
  Bundler.setup
rescue Bundler::GemNotFound => e
  STDERR.puts e.message
  STDERR.puts "Try running `bundle install`."
  exit!
end if File.exist?(gemfile)

gemfile

# my_engine/Gemfile
source :gemcutter

gem 'rails', '3.0.3'
gem 'rake'

gem 'devise', '>=1.2.rc'
gem 'declarative_authorization', '0.5.2'

group :test do
  gem "cucumber"
  gem "cucumber-rails"
  gem "database_cleaner"
  gem "capybara", ">= 0.4.0"
  gem "capybara-envjs"
  gem "culerity"
  gem "webrat"
  gem "rspec-rails", ">= 2.4.0"
  gem "jeweler"
end

我还试图像我这样要求我的引擎

gem "my_engine", :path => "./"

Gemfile和gem都已加载(Bundler.setup贯穿,Devise常量可用)。
现在我创建了一个使用my_engine gem的外部应用程序。当我从我的引擎复制测试并运行它们时,它们都会通过。

我有什么遗漏的吗?也许有更好的方法来为引擎编写测试?

1 个答案:

答案 0 :(得分:3)

多么可怕的耻辱,我忘了将设计初始化程序添加到虚拟应用程序中。不知何故,我为我的外部应用程序考虑了这一点。使用初始化程序,它可以完美运行。