Search code examples
pythonunit-testingflaskflask-sqlalchemyflask-testing

How to test redirect to created instance in Flask


Having following function in views.py:

def ask_question():
        form = QuestionForm()
        if form.validate_on_submit():
            question = Question(title=form.title.data, text=form.text.data)
            db.session.add(question)
            db.session.commit()
            return redirect('/questions/%d/' % question.id)
        return render_template('ask_question.html', form=form)

How can I get an id of created model to put it in assertion?

def test_can_post_question(self):
    response = self.tester.get('/new-question')
    self.assert_200(response)
    form = self.get_context_variable('form')
    self.assertIsInstance(form, QuestionForm)
    response = self.tester.post('/new-question', data={'title': 'What about somestuff in Flask?',
                                                       'text': 'What is it?'})
    self.assertRedirects(response, '/questions/%d' % created_question.id)
                                                     #^ how can I get id of created model here?

I'm using Flask, Flask-SQLAlchemy, Flask-Testing


Solution

  • Query the created question object. As a side effect, you can test that the question was created.

    ...
    q = Question.query.filter_by(title='What about somestuff in Flask?').first()
    self.assertRedirects(response, '/questions/%d/' % q.id)