我是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)>'
任何幫助,非常感謝。
您是否設法找到一種在Rails控制器中測試非操作方法的好方法? –