65

所以我目前正在为一个以前没有的现有控制器中的控制器编写一个测试。我要测试的是当某人不允许编辑某些东西而不是允许编辑它的人时发生的重定向。

正在编辑的控制器动作

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

因此,如果记分卡已经过审核,那么只有管理员可以编辑该分数。该控制器的路线..

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

最后是测试

  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 将被重定向回,而管理员则不会。

但是当通过 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 个响应,但我不知道从哪里开始?

任何帮助都是极好的

编辑

我可以通过这样做来测试它

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

但我从这个问题中得到了想法,听起来这可能很强大,因为它指定了重定向到的 url。

有人有这样的工作测试吗?

4

3 回答 3

73

为了使测试更具可读性,您可以这样做:(rspec ~> 3.0)

expect(response).to redirect_to(action_path)
于 2015-09-15T14:38:47.477 回答
53

这条线有问题

response.should redirect_to :back

逻辑不正确。您应该期望#edit重定向到:back您之前设置的路径,即/scorecard. 但是你设置:back在这里。在 Rspec 的上下文中,:back每个示例都应该为空。

要修改,只需将其设置为

response.should redirect_to '/scorecard'
于 2013-05-08T13:23:54.817 回答
4

用于测试是否发生了重定向,没有匹配的路由

(只是为了测试重定向,当路由太长时我使用了这个:D)。你可以简单地这样做:

expect(response.status).to eq(302) #redirected
于 2018-10-05T00:38:20.333 回答