diff --git a/scrapy/http/response/text.py b/scrapy/http/response/text.py
index b54c3e279f124e7b50318f851f42f25e0061c00f..aa1c2cb513698f4520ead4a63d7c58b5927e93ca 100644
--- a/scrapy/http/response/text.py
+++ b/scrapy/http/response/text.py
@@ -53,7 +53,7 @@ class TextResponse(Response):
super(TextResponse, self)._set_body(body)
def replace(self, *args, **kwargs):
- kwargs.setdefault('encoding', getattr(self, '_encoding', None))
+ kwargs.setdefault('encoding', self.encoding)
return Response.replace(self, *args, **kwargs)
@property
diff --git a/scrapy/tests/test_http_response.py b/scrapy/tests/test_http_response.py
index eb48d0a867b10e609f71de01ec2623807703c00d..3c95c548ffc277f46072837002aa9494cba28750 100644
--- a/scrapy/tests/test_http_response.py
+++ b/scrapy/tests/test_http_response.py
@@ -287,13 +287,16 @@ class XmlResponseTest(TextResponseTest):
r4 = r3.replace(body=body2)
self._assert_response_values(r4, 'utf-8', body2)
- # make sure replace() rediscovers the encoding (if not given explicitly) when changing the body
+ def test_replace_encoding(self):
+ # make sure replace() keeps the previous encoding unless overridden explicitly
body = """"""
- r5 = self.response_class("http://www.example.com", body=body)
body2 = """"""
+ r5 = self.response_class("http://www.example.com", body=body)
r6 = r5.replace(body=body2)
+ r7 = r5.replace(body=body2, encoding='utf-8')
self._assert_response_values(r5, 'iso-8859-1', body)
- self._assert_response_values(r6, 'utf-8', body2)
+ self._assert_response_values(r6, 'iso-8859-1', body2)
+ self._assert_response_values(r7, 'utf-8', body2)
if __name__ == "__main__":