我是 Rails 和 rspec 的新手。我的控制器中有一个自定义方法,它不是一个动作。我正在尝试使用规范测试此方法。
这是我的控制器方法:
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)>'
任何帮助深表感谢。