2015-08-27 80 views
0

我正在編寫Rails API,並試圖編寫將測試身份驗證的控制器。舉例來說,我在我的PostControllerbefore_action :authenticate這是如何在API控制器中測試身份驗證

def authenticate 
    authenticate_or_request_with_http_token do |token, options| 
    User.find_by(:auth_token => token) 
    end 
end 

這是我PostsController測試:

require 'rails_helper' 

RSpec.describe Api::PostsController, type: :controller do 

    let(:valid_attributes) { 
    { 
     "title"    => "Post title", 
     "content"    => "Post content", 
     "status"    => "published" 
    } 
    } 

    let(:invalid_attributes) { 
    { 
     "title"    => "", 
     "content"    => "", 
     "status"    => "" 
    } 
    } 

    let(:valid_session) { {} } 

    before do 
    params = { session: { email: '[email protected]', password: 'foobar' } } 
    SessionsController.create params 
    @post = Post.new({ 
     title: "Some title", 
     content: 'Some content', 
     status: "published" 
    }) 
    end 

    it "creates a new post" do 
    post :create, post: @post 
    expect(Post.count).to eq(1) 
    end 

end 

然而,上述與以下錯誤而失敗:

1) Api::PostsController creates a new post 
Failure/Error: SessionsController.create params 
NoMethodError: 
    undefined method `create' for SessionsController:Class 

任何建議?

回答

0

你不能用類SessionsController調用create行爲。更好地創建用戶對象並將其分配給request.envtoken相同。像下面的示例代碼 -

require 'rails_helper' 
RSpec.describe Api::PostsController, type: :controller do 
    before do   
    user = User.create(:auth_token => 'token') 
    request.env["HTTP_AUTHORIZATION"] = ActionController::HttpAuthentication::Token.encode_credentials("token") 
    end 
end 
+0

不幸的是,也沒有工作... – WagnerMatosUK

相關問題