ホーム > 今日のテストコード > ルーティングのテスト

ルーティングのテスト

railsのルーティングのテスト。
:id => /\d+/ と指定している部分「これじゃ部分一致では?」と思いましたが、ActionController::Routing::Route#generation_requirements で\Aと\Zで挟まれて再コンパイルされてますね。

config/routes.rb

1
2
3
4
5
6
ActionController::Routing::Routes.draw do |map|
  map.with_options(:controller => 'products') do |products|
    products.connect 'products/:id', :action => 'show', :id => /\d+/
    products.connect 'products', :action => 'create', :conditions => { :method => :post }
  end
end

spec/controllers/products_controller_spec.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
require 'spec_helper'
 
describe ProductsController do
 
  describe 'ルーティングのテスト' do
 
    it 'Products#show' do
      params_from(:get, '/products/123').should == { 
        :controller => 'products',
        :action => 'show',
        :id => '123'
      }
    end
 
    it 'idが数字のみでない場合は404' do
      lambda { 
        params_from(:get, '/products/123abc')
      }.should raise_error(ActionController::RoutingError)
    end
 
    it 'Product#create' do
      params_from(:post, '/products').should == { 
        :controller => 'products',
        :action => 'create'
      }
    end
 
    it 'createはPOSTのみ' do
      lambda { 
        params_from(:get, '/products')
      }.should raise_error(ActionController::MethodNotAllowed)
    end
 
  end
 
end

参考: