用Cucumber可以做View的接受测试,那么对控制器和模型怎么测试呢?

用RSpec写需求

安装rspec

  1. 在Gemfile文件中的group:test里面添加gem 'rspec-rails'
  2. 要测试控制器,还要添加 gem 'rails-controller-testing'
  3. 运行bundle install
  4. 在项目根目录下运行rails generate rspec:install来建立RSpec需要的文件和目录

建立查询TMDB的骨架

创建对应目录spec/controllers和文件spec/controllers/movies_controller_spec.rb

require 'rails_helper'

describe MoviesController do
  describe 'searching TMDb' do
    it 'should call the model method that performs TMDb search'
    it 'should select the Search Results template for rendering'
    it 'should make the TMDb search results available to that template'
  end
end

运行

rspec -c  spec/controllers/movies_controller_spec.rb

发现3个测试都没实现。

第一个测试

因此我们需要post一个数据测试控制器确实调用了模型的search_tmdb方法

require 'rails_helper'

describe MoviesController, type: :controller do
  describe 'searching TMDb' do
    it 'should call the model method that performs TMDb search' do
      post :search_tmdb, params:{:search_terms => 'hardware'}
    end
    it 'should select the Search Results template for rendering'
    it 'should make the TMDb search results available to that template'
  end
end

运行rspec,会发现3个测试的1个通过了,2个未实现

rspec -c  spec/controllers/movies_controller_spec.rb

但是上面的测试只有动作,没有验证数据/行为的正确性。

使用测试替身,测试控制器的行为