I've been writing a test with RequestFactory to test one of my views, with the following code:
class ViewTestCase(TestCase):
@classmethod
def setUp(self):
self.factory = RequestFactory
self.user = User.objects.create_user(
first_name='tester',
username='test1',
password='123',
email='[email protected]'
)
def test_room_creation(self):
payload = {"titlePlanning": "Test1","styleCards": "Fibonnaci","deck": ["1","2","3"]}
request = self.factory.post('/room', payload)
request.user = self.user
response = BeginRoom.as_view()(request)
self.assertEqual(response.status_code, 200)
This is the data that I need to send to use POST:
class BeginRoom(APIView):
permissions_classes = (IsAuthenticated,)
def post(self, request, format=None):
data= self.request.data
user = request.user
name = data['titlePlanning'].strip()
styleCards = data['styleCards']
cards = data['deck']
My problem is that whenever I run my tests I get the following error:
data = self._encode_json({} if data is None else data, content_type)
AttributeError: 'str' object has no attribute '_encode_json'
What should I do? I'm lost from here and can't find anything related. Any help is appreciated!
Instead of this inside test_room_creation
:
request = self.factory.post('/room', payload)
use this:
request = self.factory.post('/room', payload, content_type='application/json')
From docs:
If you provide
content_type
asapplication/json
, the data is serialized usingjson.dumps()
if it’s a dict, list, or tuple.