时可以覆盖我的控制器,即高度depeinding上ETag时单元测试?

下面就是我想要做的事: 在情况下,如果页面不陈旧(这意味着它的新鲜),我添加一些头到响应。

当我试图测试所有(RSpec的),不管我有多少类似的要求有,我仍然收到200 OK,而不是304,我的头不会被修改。此外,如果我跟踪request.fresh?(响应),它总是假的。

然而,它完美地工作在浏览器中。 我已经试过状态的ActionController :: Base.perform_caching = true时,它不会改变大局。

感谢您

有帮助吗?

解决方案 3

确定,这里是一个点:

击中请求之前,阅读了一切关系到Rails代码的ETag的 而且不要忘了设置:

request.env["HTTP_IF_MODIFIED_SINCE"]
request.env["HTTP_IF_NONE_MATCH"]

由于他们需要的ETag测试。

其他提示

下面将说明如何测试,如果第二请求返回304响应:

    get action, params
    assert_response 200, @response.body
    etag = @response.headers["ETag"]
    @request.env["HTTP_IF_NONE_MATCH"] = etag
    get action, params
    assert_response 304, @response.body

滑轨散列:ETAG你提供:

headers['ETag'] = %("#{Digest::MD5.hexdigest(ActiveSupport::Cache.expand_cache_key(etag))}")

所以设置简单的东西作为

frash_when(:etag => 'foo')

将仅由右侧消化(双引号是必要的)

触发
def with_etag
  if stale?(:etag => 'foo')
    render :text => 'OK'
  end
end

... tested by ...

@request.env['HTTP_IF_NONE_MATCH'] = '"acbd18db4cc2f85cedef654fccc4a4d8"'
get :with_etag
assert_equal 304, @response.status.to_i

同为改性:

def with_modified
  if stale?(:last_modified => 1.minute.ago)
    render :text => 'OK'
  end
end

... tested by ...

@request.env['HTTP_IF_MODIFIED_SINCE'] = 2.minutes.ago.rfc2822
get :with_modified
assert_equal 304, @response.status.to_i

这个要点是在rspec的非常有用的重新ETAG测试 -

https://gist.github.com/brettfishman/3868277

现在的Rails 4.2也需要在考虑到该摘要的模板。对我来说,工作如下:

def calculate_etag(record, template)
  Digest::MD5.hexdigest(ActiveSupport::Cache.expand_cache_key([
    record,
    controller.send(:lookup_and_digest_template, template)
  ])).inspect
end

def set_cache_headers(modified_since: nil, record: nil, template: nil)
  request.if_modified_since = modified_since.rfc2822
  request.if_none_match = calculate_etag(record, template)
end

set_cache_headers(
  modified_since: 2.days.ago,
  record: @book,
  template: 'books/index'
)

至少在滑轨5.2,szeryf的溶液失败。这种变化不工作:

get action, parms
assert_response 200, @response.code
etag = @response.headers["ETag"]
get action, parms, headers: { "HTTP_IF_NONE_MATCH": etag }
assert_response 304, @response.code

请参阅Rails的指南: HTTPS://guides.rubyonrails .ORG / testing.html#设定报头和 - CGI-变量

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top