2015-01-17 35 views
1

具有以下功能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) 

我怎樣才能創建的模型的ID來把它放在說法對嗎?

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? 

我使用燒瓶,燒瓶SQLAlchemy的,瓶測試

回答

1

查詢所創建的問題對象。作爲副作用,您可以測試問題是否已創建。

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

這就是我想到的第一個問題,但是如果有mor優雅的方式?我在SQLAlchemy文檔中發現了一些像'lastcreatedrow'方法,但無法弄清楚如何使用它的方法。 – micgeronimo

+1

@micgeronimo,您可以使用它來測試視圖。但是如果你在問題後創建另一個對象呢?它會讓你的測試變得脆弱。 – falsetru

+0

聽起來很合理。順便說一句,它是正確的'響應= self.tester.post('/新問題',數據= {'標題':'怎麼樣瓶'somestuff'','文本':'它是什麼?'))' ?當我嘗試這樣做時,我得到None,'q = Question.query.filter_by(title ='Flask中的somestuff怎麼樣?')first()' – micgeronimo

相關問題