質問

非常にユニットテストでEtagsを上depeindingされ、私のコントローラを、カバーすることは可能ですか?

ここで私がやろうとしているものです。 ページは、(それが新鮮だことを意味する)古いされていないときに、私は応答にいくつかのヘッダを付加しています。

私はそれをすべて(RSpecの)をテストしようとしているときに、私が持っているどのように多くの同様の要求に関係なく、私はまだ304の代わりに200 OKを受信し、私のヘッダーは変更されません。私はrequest.fresh?(応答)を追跡する場合はさらに、それは常にfalseです。

しかし、それは完全にブラウザで動作します。 私はすでに状態ActionControllerに試してみた:: Base.perform_caching = trueの、それは全体的な状況は変更されません。

ありがとうございます。

役に立ちましたか?

解決 3

[OK]を、ここでのポイントはあります:

の要求を打つ前に、RailsのコードでてETagに近い関連すべてを読みます そして、DOはセットすることを忘れないで:

request.env["HTTP_IF_MODIFIED_SINCE"]
request.env["HTTP_IF_NONE_MATCH"]
それらはETagの試験のために必要しているので、

他のヒント

はここで2番目のリクエストが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

Railsのハッシュ:あなたが提供した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'
)
少なくともRailsの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