开发者

RoR: Before filter returning false does not stop action form running

开发者 https://www.devze.com 2023-03-20 14:48 出处:网络
In my test, I do this: delete :destroy, :id => p.id assert_equal \"You do not have permission to delete this Object.\", flash[:error]

In my test, I do this:

     delete :destroy, :id => p.id
     assert_equal "You do not have permission to delete this Object.", flash[:error]
     Object.find_by_id(p.id).should_not be_nil #line 48 (reffed by console output below)

and my before filter, has a puts, so I know the result is false, and doesn't return

  before_filter lambda { |controller| 
      result = controller.is_object_on_same_account_as_current_account_for_id?(
                  controller_name.classify.constantize, 
                  controller.params[:id])
      puts result
      return if result
  }, :only => [:destroy]

according to this page: http://citizen428.net/archives/846, actions bound by a filter are only executed if the filter returns.

And here is the console output:

Started
false
F
Finished in 0.865708 seconds.

  1) Failure:
test: .... ...
blah blah, issue is on line 48

     shoulda (2.11.3) lib/shoulda/context.rb:382:in `...']:
expected: not nil
     got: nil

So... what is going on here? I'm completely clueless.

related code:

destroy method:

 def destroy
    @content.destroy 

Not, that I'm only running the o开发者_如何学JAVAne test.


Per the official Rails Docs, the proper way to stop an action from being executed with a before_filter is to actually redirect or render within the filter.

So you'd probably want:

before_filter lambda { |controller| 
      result = controller.is_object_on_same_account_as_current_account_for_id?(
                  controller_name.classify.constantize, 
                  controller.params[:id])
      puts result
      if !result
        flash[:error] = "You do not have permission to delete this Object."
        redirect_to "/" # or wherever you want to redirect to
      end
  }, :only => [:destroy]
0

精彩评论

暂无评论...
验证码 换一张
取 消