2016-12-04 60 views
2

我試圖用minitest訪問我的控制器中的實例變量。使用Minitest訪問控制器實例變量

例如:

microposts_controller.rb:

def destroy 
    p "*"*40 
    p @cats = 42 
end 

我將如何測試@cats裏面microposts_controller_test.rb與MINITEST價值?

我知道我可以從瀏覽器提交delete請求,並檢查我的服務器日誌,發現:

"****************************************" 
42 

another answer讀,我有機會獲得一個assigns哈希所有的實例變量,但它沒沒有工作。我也試過在controller裏面尋找物體。如下圖所示:

microposts_controller.rb:

test "@cats should exist in destroy method" do 
    delete micropost_path(@micropost) 
    p controller.instance_variables 
    p assigns[:cats] 
end 

輸出:

[:@_action_has_layout, :@_routes, :@_request, :@_response, :@_lookup_context, :@_action_name, :@_response_body, :@marked_for_same_origin_verification, :@_config, :@_url_options]0:04 
nil 

我期待看到controller物體內部的@cats實例變量。我也期待看到42正在輸出。

我在這裏錯過了什麼?

回答

0

我有一個before_action,檢查以確保用戶登錄,所以delete請求得到重定向。

我也有一個測試助手,將有效的用戶ID放入會話中。使用一切正常:)

microposts_controller_test.rb:

test "@cats should exist?" do 
    log_in_as(users(:michael)) 
    delete micropost_path(@micropost) 
    p controller.instance_variables 
    p assigns[:cats] 
end 

test_helper.rb中:

def log_in_as(user) 
    session[:user_id] = user.id 
end 

輸出:

[:@_action_has_layout, :@_routes, :@_request, :@_response, :@_lookup_context, :@_action_name, :@_response_body, :@marked_for_same_origin_verification, :@_config, :@current_user, :@_params, :@micropost, :@cats, :@_url_options] 
42