rails rspec mock_model期望的对象,得到String

时间:2012-01-11 00:48:02

标签: ruby rspec

我有一个目录控制器和一个文件控制器。我正在测试Files控制器。我已经为File创建了有效的属性,我正在尝试mock_model目录以使测试通过。 GET测试所有工作,但没有一个POST测试工作。 POST测试都给出了错误:“目录预期,得到字符串。”

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”=&gt;“1011”)。所以我不确定为什么mock_model没有创建对象?

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

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

1 个答案:

答案 0 :(得分:1)

在params哈希中传递mock的id而不是mock本身。您还需要存根查找方法,以便模拟在控制器操作中可用:

@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