2012-12-20 39 views
1

我是rails和rspec的新手。我在我的控制器中有一個自定義方法,這不是一個動作。我試圖用spec來測試這個方法。無法訪問從rspec測試中定義的控制器方法中的flash [:error]

這裏是我的控制器方法:

def find_target_by_id(target_id)  
    begin 
     @target = Target.find(target_id) 
    rescue ActiveRecord::RecordNotFound 
     flash[:error] = "Target with Id #{target_id} does not exist." 
     redirect_to root_url 
    end 
end 

這裏是我的這個方法RSpec的測試:

context "is given invalid id" do 
    before do 
    Target.stub(:find).with("1").and_raise(ActiveRecord::RecordNotFound) 
    end 
    it "returns flash[:error] " do 
    TargetsController.new.find_target_by_id("1") 
    flash[:error].should eq("Target with Id 1 does not exist.") 
    end 

    it "redirects to root url " do 
     TargetsController.new.find_target_by_id("1") 
     response.should redirect_to(root_url) 
    end 
end 

但是,當運行測試,我得到的錯誤:

Failure/Error: TargetsController.new.find_target_by_id("1").should have(flash[:error]) 
RuntimeError: 
    ActionController::Base#flash delegated to request.flash, but request is nil: #<TargetsController:0x007fced708ae50 @_routes=nil, @_action_has_layout=true, @_headers={"Content-Type"=>"text/html"}, @_status=200, @_request=nil, @_response=nil> 
# ./app/controllers/targets_controller.rb:71:in `find_target_by_id' 
# ./spec/controllers/targets_controller_spec.rb:212:in `block (4 levels) in <top (required)>' 

任何幫助,非常感謝。

+0

您是否設法找到一種在Rails控制器中測試非操作方法的好方法? –

回答

1

您不能訪問Rspec中的閃存,除非實際的Web請求已經完成。這就是錯誤提示 - 它正在查看request.flash,但request爲零,因爲您還沒有發出網絡請求。

幾個想法:

  • 請在您的測試一個GET(或POST或其他)請求調用此方法的動作,所以你其實可以有機會獲得閃光
  • 不要設置在你的幫手方法中閃光,但相反返回一個錯誤信息或引發異常,並保留閃光燈消息設置爲您的控制器行動

如果我在這種情況下,我會採取第二種方法。把控制器的東西放在控制器的操作上(比如設置flash和whatnot),並保持你的幫助器方法簡單明瞭。它肯定會幫助你保持簡單的測試。

+0

謝謝BaronVonBraun的快速回復。我現在看到它。我在這個輔助方法中設置flash的原因是因爲這是由控制器內的多個動作調用的。因此,如果我將錯誤設置爲控制器操作,我的代碼中會有很多冗餘。我很困惑... –

相關問題