如何在 RSpec 中普遍覆盖 get 和 post 方法? [英] How can you universally override the get and post methods in RSpec?

查看:61
本文介绍了如何在 RSpec 中普遍覆盖 get 和 post 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想覆盖 RSpec 中的 getpost 方法.

我想这样做是为了在我的测试中处理子域.据我所知,处理子域的唯一方法是在每次调用之前更改 @request 对象.我可以在每次测试之前都这样做,但这会导致一些非常混乱的代码.

为了保持干燥,我尝试在 spec_helper.rb 中使用 config.before(:each) 方法,但这似乎不是在与测试相同的范围内运行,并且无权访问 @request.

因此,我的下一个最佳方法是覆盖在正确范围内的 getpost.

def get *args@request.host = @required_domain 如果@required_domain超级*参数结尾

我可以将此代码包含在每个规范文件的顶部,但我宁愿将其设置为通用.如果我在 spec_helper.rb 中设置它,尽管它没有被调用.

在哪里可以设置它来覆盖默认的 get 方法?

解决方案

<块引用>

然而,这似乎与测试不在同一范围内运行.

这不太对 - 它在相同的范围内运行,但是在配置 @request 之前,所以它没有效果.

试试这个:

模块请求扩展定义获取(*)@request.host = @required_domain 如果@required_domain极好的结尾结尾RSpec.configure 做 |c|c.include RequestExtensions, :type =>:控制器结尾

HTH,大卫

I'd like to override the get and post methods in RSpec.

I want to do this in order to deal with subdomains in my tests. As far as I can tell, the only way to deal with subdomains is to alter the @request object before each call. I could do this before each and every test but that's going to lead to some really messy code.

In an effort to keep things DRY I've tried using a config.before(:each) method in spec_helper.rb however this doesn't seem to be run in the same scope as the test and doesn't have access to @request.

My next bsest approach is therefore to overrride get and post which are in the correct scope.

def get *args
  @request.host = @required_domain if @required_domain
  super *args
end

I can include this code in the top of each spec file but I'd rather set it universally. If I set it in spec_helper.rb though it does not get called.

Where can I set this to override the default get method?

解决方案

however this doesn't seem to be run in the same scope as the test.

That's not quite right - it's run in the same scope, but before @request is configured, so it has no effect.

Try this:

module RequestExtensions
  def get(*)
    @request.host = @required_domain if @required_domain
    super
  end
end

RSpec.configure do |c|
  c.include RequestExtensions, :type => :controller
end

HTH, David

这篇关于如何在 RSpec 中普遍覆盖 get 和 post 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆