我是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控制器中测试非操作方法的好方法? –