2016-11-26 9 views
1

は、私は、ランダムなレシピの役割を果たすことができる機能を備えたRailsアプリケーションの構築:Railsはunknowパラメータとassert_redirect_to

class RecipesController < ApplicationController 

    # GET /recipes/shuffle 
    # get a random recipe and redirect user on this 
    def shuffle 
     offset = rand Recipe.count 
     random = Recipe.offset(offset).first 
     redirect_to recipe_path random 
    end 

end 

それは素晴らしい仕事を、私はこのルート上でテストを構築したい

require 'test_helper' 

class RecipesControllerTest < ActionController::TestCase 

    test "should be redirect to a random recipe path" do 
    get :shuffle 
    assert_redirected_to( controller: "recipes", action: "show" ) 
    end 

end 

しかし、私はこのエラーメッセージを得るため、実際には動作しません:

ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"recipes"}

ここに私のRを oute.rb:

RaspberryCook::Application.routes.draw do 

    resources :recipes, :only => [:index, :new , :create , :destroy , :edit] 
    get  'recipes/:id' ,   to: 'recipes#show', id: /[0-9]+/ 
    patch 'recipes/:id' ,   to: 'recipes#update', id: /[0-9]+/ 
    get 'recipes/shuffle' ,  to: 'recipes#shuffle' 
    post 'recipes/import' ,  to: 'recipes#import' 

end 

それでは、どのように私は、「未知のIDを持つランダムなレシピを取得する必要があります」のような私のテストを構築することができますか?

+0

対応するルートを 'routes.rb'で定義しましたか?あなたの 'routes.rb'はどのように見えますか? – Rashmirathi

+0

@Rashmirathi、私は自分の投稿を編集しました。私は* route.rbを追加しました。* – RousseauAlexandre

+0

はおそらくあなたの 'asset_redirected_to'にIDを渡します。 –

答えて

0

私は自分自身と私はこのような単純な正規表現マッチャ使用する溶液が見つかりました:

require 'test_helper' 

class RecipesControllerTest < ActionController::TestCase 

    test "should be redirect to a random recipe path" do 
    get :shuffle 
    assert_redirected_to %r(/recipes/[0-9]+) 
    end 

end 

簡単にそれが仕事をしていませんが!

1

この場合、テストを通してアクセスする方法がないということで、コントローラメソッド内に変数が生成されています。

テストされるメソッドの内部変数を参照するのが一般的な要件であり、 '模擬'または 'スタブ'のコメントが役立ちます。

ここで、randコールの結果をスタブして、所定の数値を返すことができます。これは、すべてのテスト・ケースで行うことができます

id = 1 
expect(Kernel).to receive(:rand).with(Recipe.count).and_return(id) 
get :shuffle 
assert_redirected_to(controller: "recipes", action: "show", id: id) 
+0

これはうまくいきません。NoMethodError:未定義のメソッド' expect 'が# 'にあります(** rspec **を使わないので?) – RousseauAlexandre

+0

はい、rspEcを使用していないからです。あなたはおそらくあなたが使っているライブラリをテストしています。 –

関連する問題