2012-01-11 69 views
0

我有一个目录控制器和一个文件控制器。我正在测试文件控制器。我已经为该文件创建了有效的属性,我试图mock_model目录来让测试通过。 GET测试全部正常,但POST测试均无效。 POST测试都给出了错误:“预期的目录,得到了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中文件,它表明组件是一个字符串( “组件”=> “1011”)。所以我不确定为什么mock_model没有创建一个对象?

我使用存根试过!而不是mock_model,但由于创建而变得复杂!用于存根!需要很多自己的有效变量集,而且我根本不想为那些甚至根本不测试目录控制器的人设置一大堆其他有效属性。

我在做什么错在这里我的方法?

回答

1

传递模拟的ID在params哈希表,而不是模仿本身。您还需要存根查找方法,以便模拟控制器中的行为是有效的:

@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 
相关问题