如何从jquery文件上传中为json响应编写rspec测试

时间:2011-07-19 02:26:34

标签: ruby-on-rails-3 rspec2

我有一个使用jquery-file-upload插件的表单。它发布到控制器,返回对象都是json类型。

控制器

def create
  @upload = Upload.new(params[:upload])
  if @upload.save
    render :json => [ @upload.to_jq_upload ].to_json
  else
    render :json => [ @upload.to_jq_upload.merge({ :error => "custom_failure" }) ].to_json
  end
end

我有以下rspec测试:

describe "post 'create' " do
  before(:each) do
    @upload = Factory(:upload)
    @attr_upload = {:photo => sample_file}
  end

  describe "success" do
    it "should  create a new upload object" do
      lambda do
        post :create, :upload => @attr_upload, :format => :json
      end.should change(Upload, :count).by(1)
    end
  end
end

哪个有效。我想测试两个失败,因为在没有文件的情况下发布的表单或文件太大或格式错误。

这是我的测试。

describe "failure" do
  before(:each) do
    @upload = Factory(:upload)
    @attr_upload = {:photo => sample_file("too_big.jpg")}
  end

  it "should not create a new upload object" do
    lambda do
      post :create, :upload => @attr_upload, :format => :json
    end.should_not change(Upload, :count).by(1)
  end
end

这不起作用。这是错误:

ActionController::RoutingError:
No route matches {:action=>"show", :controller=>"uploads", :id=>#<Upload id: nil, created_at: nil, updated_at: nil, photo_file_name: "too_big.jpg", photo_content_type: "image/jpeg", photo_file_size: 7483326, photo_updated_at: "2011-07-19 02:24:06">}

这是我的路线档案:

Hbg::Application.routes.draw do      
  resources :uploads
end

为什么在将表单提交到“创建”操作时出现此错误?响应应该是一个json对象。

0 个答案:

没有答案