2013-07-15 40 views
4

我使用下面的代码从一个耙子任务中在服务器上执行的请求:强制的Rails的app.get重做请求

app = ActionDispatch::Integration::Session.new(Rails.application) 
app.host!('localhost:3000') 
app.get(path) 

这种运作良好。

但是,如果我再次调用app.get(path)具有相同路径,则不会重复该请求,并返回以前的结果。

有没有一种方法可以强制app.get重复调用?

+1

你怎么知道第二个'app.get(path)'不重复请求?我只是查看了“ActionDispatch :: Integration :: Session”的代码,并没有指出任何缓存。 – henrikhodne

+0

@henrikhodne控制器中存在的任何'puts'方法将为第一个请求输出路由。 –

+0

@henrikhodne你是对的。它不是执行任何缓存的'ActionDispatch :: Integration :: Session',而是标准的rails缓存管道做的事情,就像标准的HTTP请求一样。我已经详细阐述了我的答案。 –

回答

1

我已经弄清楚发生了什么事情。

基本上,“请求不重复”的观察结果是Rails自己的缓存行为。有意义的是,app.get被视为任何其他请求,如果启用了缓存,则会返回缓存,如果不是,则会重复(如@henrikhodne声明的那样)。这就解释了为什么缓存控制器中的puts第二次不会输出。

要验证,请在2个控制器方法中添加一个puts,但仅在第二个方法中设置expires_in。第一个将重复输出,第二个不会。

强制重复请求的方法是通过修改URL来缓存缓存。与使用HTTP时一样, app.get("/")将变为app.get("/?r=123456")。事后看来这一切似乎都很明显,基本上app.get被完全视为客户端请求,并且所有相同的规则都适用。

1

尝试重置会话:

app.reset! 

这里是如何工作的,当复位,

def reset! 
    @https = false 
    @controller = @request = @response = nil 
    @_mock_session = nil 
    @request_count = 0 
    @url_options = nil 

    self.host  = DEFAULT_HOST 
    self.remote_addr = "127.0.0.1" 
    self.accept  = "text/xml,application/xml,application/xhtml+xml," + 
         "text/html;q=0.9,text/plain;q=0.8,image/png," + 
         "*/*;q=0.5" 

    unless defined? @named_routes_configured 
     # the helpers are made protected by default--we make them public for 
     # easier access during testing and troubleshooting. 
     @named_routes_configured = true 
    end 
    end 

否则将只是重新使用最后一个响应:

# this is a private method in Session, it will called every time you call `get/post, etc` 
def process 
    ...... 
    @request_count += 1 
    @request = ActionDispatch::Request.new(session.last_request.env) 
    response = _mock_session.last_response 
    @response = ActionDispatch::TestResponse.new(response.status, response.headers, response.body) 
    @html_document = nil 
    .... 
end 

祝你好运!

+1

它实际上不重用最后一个响应。如果你在代码中看起来更深一层,它会将请求发送到'_mock_session',覆盖'last_response'属性。不过,'#reset!'可能仍然有效。 – henrikhodne

+0

'app.reset!'在我的测试中没有影响。我的问题是铁路自己的缓存系统被激活(因为它是一个正常的HTTP请求),请参阅我的答案。我感谢你的帮助,虽然这调查! –