所以我目前正在为一个以前没有的现有控制器中的控制器编写一个测试。我要测试的是当某人不允许编辑某些东西而不是允许编辑它的人时发生的重定向。
正在编辑的控制器动作
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。
有人有这样的工作测试吗?