2015-10-11 83 views
0

我想用RSpec測試我的Rails應用程序,但是我的測試失敗了,因爲RSpec似乎沒有通過我給Rails的頭文件。爲什麼RSpec不會將我的標頭傳遞給Rails?

我有一個UsersController,其中包括ApplicationHelper,並在ApplicationHelper我有一個方法訪問headers散列。通過我的SESSION_KEY標題將其索引返回nil。如果在該方法中使用puts headers,則散列不包含我提供的標題,只有以下內容:{"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff"}

這裏是我的RSpec規範的相關部分:

require 'rails_helper' 

describe Api::V1::UsersController, type: :request do 
    let(:user) { User.create(name: 'TestUser', email: '[email protected]', password: 'password123', password_confirmation: 'password123') } 
    let(:id) { user.id } 
    let(:sess) { user.sessions.create } 

    before { get "/api/v1/users/#{id}" } 

    # Snipped other tests 

    context 'with authentication' do 
    context 'with a valid id' do 
     it 'returns full user information' do 
     get "/api/v1/users/#{id}", nil, {'HTTP_SESSION_KEY': sess.key} 
     response_user = response_json[:user] 
     expect(response.status).to eq 200 
     expect(response_user).to_not be_nil 
     expect(response_user[:name]).to eq user[:name] 
     expect(response_user[:email]).to eq user[:email] 
     end 
    end 
    end 

    def response_json 
    JSON.parse(response.body, symbolize_names: true) 
    end 
end 

我也試圖傳遞SESSION_KEY頭不HTTP_之前,並沒有奏效。我也嘗試將它移動到before塊中的頂部get,以查看它是否是上下文問題,並且也不起作用。

+0

請注意,'{'HTTP_SESSION_KEY':sess.key}'應該與hashrocket:'{'HTTP_SESSION_KEY'=> sess.key}' – nsave

+0

@nsave第一次我認爲這可能是我的問題的根源,但它不是......任何想法可能是什麼? – AppleDash

+0

看來你每次都在做'2'''請求,第一個在''before''塊中,第二個在'it'塊中。這是故意的嗎? –

回答

1

文檔說上面要工作,但如果由於某種原因,RSpec的是解釋測試作爲:controller測試,而不是一個:request測試,那麼你需要做的(只是你get調用之前):

request.env["HTTP_SESSION_KEY"] = sess.key 
+0

這似乎沒有做任何事情,根據控制器的標題哈希保持不變。 – AppleDash

相關問題