下面是一个来自 gem 的 Rails 控制器集成测试的一个很好的最小示例。
my_gem
. 假设您位于具有简单 rspec 设置的 gem 根目录中(例如使用rspec --init
)。然后spec/rails_controller_integration_spec.rb
会是这个样子。
rspec/rails
是否有必要的要求,其中包括rspec/rails/example
基于元标记设置示例组类型。元标记:type => :controller
驱动包含适当的组模块RSpec::Rails::ControllerExampleGroup
,它为您提供rails 控制器规范的所有好东西以及ActionController::TestCase
get/post
like 的所有好东西。
希望这可以帮助。
我仍然不明白 Rails 环境是如何分配的。特别是如果我想设置两个应用程序TestTailsApp1
和TestTailsApp2
. 有什么建议吗?
require 'spec_helper'
require 'my_gem'
require 'rails'
require 'action_controller/railtie' # allows ActionController::Base
# crucial part here:
require 'rspec/rails'
# note that require 'rspec-rails' does not work
module TestRailsApp
class Application < Rails::Application
# app config here
# config.secret_token = '572c86f5ede338bd8aba8dae0fd3a326aabababc98d1e6ce34b9f5'
# routes.draw do
# resources :models
# end
end
class ApplicationController < ActionController::Base
# setup
end
end
describe 'My gem' do
context "in a Rails controller", :type => :controller do
controller(TestRailsApp::ApplicationController) do
extend(RSpec::Rails::ControllerExampleGroup::BypassRescue)
# example-specific setup for anonymous controller
# https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs/anonymous-controller
def index
end
end
before(:each) do
# request needs to be setup to avoid path setting error
@request = ActionController::TestRequest.new
end
describe "#index" do
it "works" do
get :index
response.body.should == 'index content'
end
end
end
end