RSPEC -RAILS-如何跟随重定向
-
30-09-2019 - |
题
有人知道如何使RSPEC遵循重定向(在控制器规格中)吗? (例如,测试/单元已关注_redirect!)
我尝试了“关注_redirect!”和“关注_redirect”,但只能得到
undefined method `follow_redirect!' for #<Spec::Rails::Example::ControllerExampleGroup::Subclass_1:0xb6df5294>
例如:
当我创建一个帐户时,页面被重定向到帐户页面,我的新帐户应位于列表的顶部。
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
但是跟随_redirect!需要更改为实际有效的东西。
解决方案
如果要测试重定向,则移至RSPEC-RAILS域之外。
您可以使用Webrat或其他某些集成测试框架来测试这一点。
解决此问题的最简单方法不采用集成测试,可能是嘲笑导致重定向的方法。
其他提示
我认为这是 RSPEC轨道 从某种意义上说,您可以对响应状态和/或路径设置期望并测试成功。
例如:
it "should create an account" do
post :create
response.code.should == "302"
response.should redirect_to(accounts_path)
end
您可以使用
response.headers['Location']
然后,您可以直接要求。
尝试使用集成/请求测试。他们通过路由到控制器来使用类似Web的操作。例如:我有File中的Rails 2应用程序 /spec/integration/fps_spec.rb
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
适用于创建,但是重定向后,它返回401,需要新的授权。因此,我必须在2个测试中将其拆分:创建并显示创建结果。
规格不范围,如果要遵循重定向使用请求规格,则等同于测试中的集成测试::单元。
在请求规格中 follow_redirect!
工作和测试::单元。
或者,如果您想立即重定向 _via_redirect
作为动词的后缀,示例:
post_via_redirect :create, user: @user
对于RSPEC / Capybara + Rails
response_headers['Location']
但是,只有在重定向之前没有延迟时,它才能起作用。如果在那里,那么很难遵循逻辑。
不隶属于 StackOverflow