如何使用Ruby MINITEST ::规格和Rails的API集成测试?(How to use R

2019-07-29 11:44发布

我建立包括一个Rails API的应用程序,并希望使用Ruby MINITEST ::规格进行测试。

什么是设置它的好办法?

例如,良好的目录组织,很好的办法,包括文件,等等?

我使用的是在这本书的Rails 3在使用RSpec的和对API的一个伟大的篇章行动准则。 大的变化是宁愿MINITEST ::规格。

Answer 1:

什么我迄今发现的情况下,它是有帮助的其他开发人员回答....

规格/ 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

应用程序/控制器/ 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

配置/ routes.rb中

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

的Gemfile

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


文章来源: How to use Ruby MiniTest::Spec with Rails for API integration tests?