Rspec – Rails – 如何遵循redirect

有谁知道如何使rspec遵循redirect(在控制器规范)? (例如,testing/单元具有follow_redirect!)

我试过“follow_redirect!” 和“follow_redirect”,但只能得到

undefined method `follow_redirect!' for #<Spec::Rails::Example::ControllerExampleGroup::Subclass_1:0xb6df5294> 

例如:
当我创build一个帐户,该页面被redirect到帐户页面,我的新帐户应该在列表的顶部。

 it "should create an account" do post :create, :name => "My New Account" FOLLOW_REDIRECT! response.code.should == "200" accounts = assigns[:accounts] accounts[0].name.should == "My New Account" end 

但是FOLLOW_REDIRECT! 需要改变成实际工作的东西。

如果你想testingredirect,你将移动到rspec-rails域之外。

您可以使用Webrat或其他集成testing框架来testing。

解决这个问题最简单的方法就是去模拟出导致redirect的方法。

我认为这是rspec-rails控制器testing的默认行为,因为您可以设置对响应状态和/或path的期望,并testing成功。

例如:

 it "should create an account" do post :create response.code.should == "302" response.should redirect_to(accounts_path) end 

您可以通过访问redirect位置

 response.headers['Location'] 

你可以直接请求。

尝试使用集成/请求testing。 他们通过路由到控制器来使用networking访问。 例如:我有文件/spec/integration/fps_spec.rb Rails 2应用程序

  require 'spec_helper' describe "FinPoradci" do it "POST /fps.html with params" do fp_params={:accord_id => "FP99998", :under_acc => "OM001", :first_name => "Pavel", :last_name => "Novy"} fp_test=FinPoradce.new(fp_params) #after create follow redirection to show post_via_redirect "/fps", {:fp => fp_params} response.response_code.should == 200 # => :found , not 302 :created new_fp=assigns(:fp) new_fp.should_not be_empty new_fp.errors.should be_empty flash[:error].should be_empty flash[:notice].should_not be_empty response.should render_template(:show) end end 

它的工作。 直到你想发送头(基本的http授权)。

  env={'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Basic.encode_credentials(user,password)} post_via_redirect "/fps", {:fp => fp_params}, env 

创build好,但redirect后返回401,需要新的授权。 所以我必须把它分成两个testing:创造和创造的结果。

规范超出了范围,如果你想遵循redirect使用请求规范,相当于Test :: Unit中的集成testing。

在请求specs follow_redirect! 和Test :: Unit一样。

或者,如果要立即redirect,请使用_via_redirect作为动词的后缀,例如:

 post_via_redirect :create, user: @user 

RSpec / Capybara + Rails

 response_headers['Location'] 

但是,只有在redirect之前没有延迟的情况下,它才有效。 如果在那里,那么就很难遵循逻辑。