Rails / Rspec – 在控制器中testingredirect

所以我目前正在写一个控制器在现有的控制器testing,只是没有一个之前。 我想testing的是一个redirect,当有人不允许编辑某个人或允许编辑某人的时候发生。

控制器操作正在编辑

def edit if !@scorecard.reviewed? || admin? @company = @scorecard.company @custom_css_include = "confirmation_page" else redirect_to :back end end 

所以如果一个记分卡已被审查,那么只有一个pipe理员可以编辑该分数。 该控制器的路线..

 # scorecards resources :scorecards do member do get 'report' end resources :inaccuracy_reports, :only => [:new, :create] end 

最后是testing

  require 'spec_helper' describe ScorecardsController do describe "GET edit" do before(:each) do @agency = Factory(:agency) @va = Factory(:va_user, :agency => @agency) @admin = Factory(:admin) @company = Factory(:company) @scorecard = Factory(:scorecard, :level => 1, :company => @company, :agency => @agency, :reviewed => true) request.env["HTTP_REFERER"] = "/scorecard" end context "as a admin" do before(:each) do controller.stub(:current_user).and_return @admin end it "allows you to edit a reviewed scorecard" do get 'edit', :id => @scorecard.id response.status.should be(200) end end context "as a va_user" do before(:each) do controller.stub(:current_user).and_return @va end it "does not allow you to edit a reviewed scorecard" do get 'edit', :id => @scorecard.id response.should redirect_to :back end end end end 

所以试图编辑审查分数时,VA将被redirect回,pipe理员将不会。

但是当通过rspec运行这个我得到

 ScorecardsController GET edit as a admin allows you to edit a reviewed scorecard as a va_user does not allow you to edit a reviewed scorecard (FAILED - 1) Failures: 1) ScorecardsController GET edit as a va_user does not allow you to edit a reviewed scorecard Failure/Error: response.should redirect_to :back Expected response to be a redirect to </scorecard> but was a redirect to <http://test.host/> # ./spec/controllers/scorecards_controller_spec.rb:33:in `block (4 levels) in <top (required)>' Finished in 0.48517 seconds 2 examples, 1 failure 

所以我不知道如果它的工作或没有,因为我设置request.env["HTTP_REFERER"] = "/scorecard"作为应该是的地方:back那里。 还是我想念所有在一起看着httpstatus有300个答复,我可以使用,但我不知道从哪里开始呢?

任何帮助都是极好的

编辑

我可以通过这样做来testing它

 ... response.status.should be(302) 

但我从这个问题的想法,这听起来像这可能是强大的,因为它指定的URLredirect到。

任何人都有这样的工作testing

这条线有问题

 response.should redirect_to :back 

逻辑不正确。 您应该期望#editredirect到:back您之前设置的:backpath,即/scorecard 。 但是你设置了:back这里。 在Rspec的上下文中, :back应该在每个例子中都是空的。

要修改,只需将其设置为

 response.should redirect_to '/scorecard' 

为了使testing更可读,你可以这样做:(rspec〜> 3.0)

 expect(response).to redirect_to(action_path)