12

I'm building an app including a Rails API and want to use Ruby MiniTest::Spec to test.

What's a good way to set it up?

For example, good directory organization, good way to include files, etc.?

I'm using the guidelines in the book Rails 3 In Action which uses RSpec and has a great chapter on APIs. The big change is preferring MiniTest::Spec.

4

1 回答 1

18

回答我迄今为止发现的内容,以防它对其他开发人员有帮助......

规范/api/items_spec.rb

require 'spec_helper'

class ItemsSpec < ActionDispatch::IntegrationTest

  before do
    @item = Factory.create(:item)
  end

  describe "items that are viewable by this user" do
    it "responds with good json" do
      get "/api/items.json"
      response.success?.must_equal true
      body.must_equal Item.all.to_json
      items = JSON.parse(response.body)
      items.any?{|x| x["name"] == @item.name}.must_equal true
    end
  end

end

规范/spec_helper.rb

ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
gem 'minitest'
require 'minitest/autorun'
require 'action_controller/test_case'
require 'capybara/rails'
require 'rails/test_help'
require 'miniskirt'
require 'factories'
require 'mocha'

# Support files                                                                                                                                                                                                                                                                  
Dir["#{File.expand_path(File.dirname(__FILE__))}/support/*.rb"].each do |file|
  require file
end

规格/工厂/item.rb

Factory.define :item do |x|
  x.name { "Foo" }
结尾

应用程序/控制器/api/base_controller.rb

class Api::BaseController < ActionController::Base
  respond_to :json
end

应用程序/控制器/api/items_controller.rb

class Api::ItemsController < Api::BaseController
  def index
    respond_with(Item.all)
  end
end

配置/路由.rb

MyApp::Application.routes.draw do
  namespace :api do
    resources :items
  end
end

宝石文件

组:开发,:测试做
  gem 'capybara' # 在网站上模拟用户的集成测试工具。
  gem 'capybara_minitest_spec' # MiniTest::Spec 对 Capybara 节点匹配器的期望。
  gem 'mocha' # 用于 Ruby 测试替身的模拟和存根库。
  gem 'minitest', '>= 3' # Ruby 的核心 TDD、BDD、模拟和基准测试。
  gem 'minitest-capybara' # 将 Capybara 驱动切换参数添加到 minitest/spec.
  gem 'minitest-matchers' # 用于 minitest 的 RSpec/Shoulda 风格的匹配器。
  gem 'minitest-metadata' # 使用元数据键值对注释测试。
  gem 'minitest-spec-rails' # 加入 MiniTest::Spec 对 Rails 3 的支持。
  gem 'miniskirt' # 与 minitest 一起使用的工厂创建者。
  gem 'ruby-prof' # 带有原生 C 代码的 Ruby 快速代码分析器。
结尾
于 2012-05-22T00:47:59.937 回答