为什么我的回答

时间:2014-08-07 14:54:55

标签: ruby-on-rails ruby ruby-on-rails-4 rspec

以下是测试类。我在找到帐户时收到response.body as empty

require 'spec_helper'

describe ProjectController, :type => :controller do
  before(:all) do
    @acc = FactoryGirl.create(:project, name: "test", 
                   description: "Something about test");
    user = User.login(FactoryGirl.create(:user, email: "test@test.com", 
                    password: "test", code: 0));
    if user
      @auth = user['auth_token']
    end
  end

  it "can find an account" do 
    Account.find(id: 2055, authorization: @auth);
    hashed_response = {
        "@type" => "test",
        "createdAt" => "2014-07-24T15:26:49",
        "description" => "Something about test",
        "disabled" => false
    }

    expect(response.status).to eq 200    
    expect(response.body).to eq(hashed_response.to_json);

  end

end

当我尝试find Account时,它会得到结果,但为什么我的response.body为空。以下是我在 log / test for Account.find

中的回复
{
    "@type": "res",
    "createdAt": "2014-07-24T15:26:49",
    "description": "test",
    "disabled": false
}

1 个答案:

答案 0 :(得分:2)

Account.find(id: 2055, authorization: @auth)将返回Account对象,而不是响应,因为它是ORM请求而不是Web请求。如果您要测试Web请求响应,则需要先提出请求。

我认为你的测试应该是这样的:

it "can find an account" do
  Account.should_receive(:find, with: {id: 2055, authorization: @auth}

  get :show, id: 2055 # you might need to pass in some auth details also

  hashed_response = {
    "@type" => "test",
    "createdAt" => "2014-07-24T15:26:49",
    "description" => "Something about test",
    "disabled" => false
  }
  expect(response.status).to eq 200    
  expect(response.body).to eq(hashed_response.to_json);

end