2012-01-11 17 views
0

私はディレクトリコントローラとファイルコントローラを持っています。私はファイルコントローラをテストしています。 Fileの有効な属性を作成しました。テストをパスするために、ディレクトリをmock_modelしようとしています。 GETはすべての作業をテストしますが、POSTテストのどれも動作しません。 POSTテストでは、すべて "Directory expected、got String"というエラーが返されます。rails rspec mock_modelオブジェクトが予想され、文字列があります

describe FilesController do 
    def valid_attributes { 
     :name => "test", 
     :reference_id => 1, 
     :location => "/path/to/directory", 
     :software => "excel", 
     :software_version => "2010", 
     :directory => mock_model(Directory) 
    } 
    end 

describe "POST create" do 
    describe "with valid params" do 
    it "creates a new AssemblyFile" do 
     expect { 
     post :create, :assembly_file => valid_attributes 
     }.to change(AssemblyFile, :count).by(1) 
    end 

    it "assigns a newly created assembly_file as @assembly_file" do 
     post :create, :assembly_file => valid_attributes 
     assigns(:assembly_file).should be_a(AssemblyFile) 
     assigns(:assembly_file).should be_persisted 
    end 

    it "redirects to the created assembly_file" do 
     post :create, :assembly_file => valid_attributes 
     response.should redirect_to(AssemblyFile.last) 
    end 
    end 
end 

1) FilesController POST create with valid params creates a new File 
Failure/Error: post :create, :file => valid_attributes 
ActiveRecord::AssociationTypeMismatch: 
    Directory(#87017560) expected, got String(#49965220) 
# ./app/controllers/files_controller.rb:60:in `new' 
# ./app/controllers/files_controller.rb:60:in `create' 
# ./spec/controllers/files_controller_spec.rb:79:in `block (5 levels) in <top (required)>' 
# ./spec/controllers/files_controller_spec.rb:78:in `block (4 levels) in <top (required)>' 

test.logファイルを見ると、アセンブリが文字列( "assembly" => "1011")であることがわかります。だから私はなぜmock_modelがオブジェクトを作成していないのか分かりません。

私はスタブを使用してみました! mock_modelではなく、作成するために複雑になる!スタブに使用!それ自身の有効な変数がたくさん設定されている必要があります。Directory Controllerをまったくテストしようとしていないときに、他の有効な属性を設定する必要はありません。

私のアプローチでは何が間違っていますか?

答えて

1

はparamsハッシュでモックの代わりにモック自体のIDを渡します。コントローラメソッドでモックが利用できるようにfindメソッドをスタブする必要もあります:

@directory = mock_model(Directory) 
Directory.stub(:find).with(@directory.id).and_return(@directory) 
post :create, :assembly_file => valid_attributes.merge(:directory_id => @directory.id) 

# in controller 
@directory = Directory.find(params[:assembly_file][:directory_id]) # => returns the mock 
関連する問題