我正在构建一个包含 Rails API 的应用程序,并希望使用 Ruby MiniTest::Spec 进行测试。
设置它的好方法是什么?
例如,良好的目录组织、包含文件的好方法等?
我正在使用 Rails 3 In Action 一书中的指南,该书使用 RSpec 并且有一个关于 API 的重要章节。最大的变化是更喜欢 MiniTest::Spec。
最佳答案
用我目前发现的内容来回答,以防对其他开发人员有帮助....
规范/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" } end
app/controllers/api/base_controller.rb
class Api::BaseController < ActionController::Base
respond_to :json
end
app/controllers/api/items_controller.rb
class Api::ItemsController < Api::BaseController
def index
respond_with(Item.all)
end
end
配置/routes.rb
MyApp::Application.routes.draw do
namespace :api do
resources :items
end
end
gem 文件
group :development, :test do gem 'capybara' # Integration test tool to simulate a user on a website. gem 'capybara_minitest_spec' # MiniTest::Spec expectations for Capybara node matchers. gem 'mocha' # Mocking and stubbing library for test doubles for Ruby. gem 'minitest', '>= 3' # Ruby's core TDD, BDD, mocking, and benchmarking. gem 'minitest-capybara' # Add Capybara driver switching parameters to minitest/spec. gem 'minitest-matchers' # RSpec/Shoulda-style matchers for minitest. gem 'minitest-metadata' # Annotate tests with metadata key-value pairs. gem 'minitest-spec-rails' # Drop in MiniTest::Spec support for Rails 3. gem 'miniskirt' # Factory creators to go with minitest. gem 'ruby-prof' # Fast code profiler for Ruby with native C code. end
关于ruby-on-rails - 如何使用 Ruby MiniTest::Spec 和 Rails 进行 API 集成测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10694355/