2017-05-12 8 views
1

私はCBVをアップデート時にテストしており、モデルインスタンスが更新されていないと思われるたびにテストしています。テスト中にモデルインスタンスを更新できません。

コンソール出力

>  self.assertEqual(product.showoff, data['showoff']) 
E  AssertionError: 'uMsvXoRJbwFeieMvoCmR' != 'showoff 33333' 
E  - uMsvXoRJbwFeieMvoCmR 
E  + showoff 33333 

views.py

class ProductUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView): 
    model = Product 
    form_class = ProductForm 
    template_name = "mainapp/product_update.html" 
    success_message = 'Successfully Updated a Product entry' 

    def dispatch(self, *args, **kwargs): 
     return super(self.__class__, self).dispatch(self.request, *args, **kwargs) 

    def form_valid(self, form): 
     self.object = form.save(commit=False) 
     #migh need to remove that line 
     #self.object.author = self.request.user 
     return super(self.__class__, self).form_valid(form) 


product_update = login_required(ProductUpdateView.as_view()) 

tests.py

def test_ProductUpdateView_should_update_the_product_content(self): 
    #Delete all Products 
    Product.objects.all().delete() 

    #Create user (fixture) 
    user = mixer.blend('auth.User', is_superuser=True) 

    #create a Product (fixture) 
    product = mixer.blend('mainapp.Product') 

    #Fields to update 
    data = dict(showoff='showoff 33333',) 

    #Preparing to post to the Update url 
    url = reverse('wadiyabi:product_update', kwargs={'pk': product.pk}) 
    request = RequestFactory().post(url, data=data) 

    #assign a user 
    request.user = user 

    #Post to Update URL 
    response = views.ProductUpdateView.as_view()(request, pk=product.pk) 

    #Assertion: status code 
    self.assertEqual(response.status_code, 200) 
    #Refresh the db and Get the latest Product 
    product.refresh_from_db() 
    product = Product.objects.get(pk=product.pk) 
    #pytest.set_trace() 

    #Assertion 
    self.assertEqual(product.showoff, data['showoff']) 

forms.py

class ProductForm(ModelForm): 
    class Meta: 
     model = Product 
     fields = ['photo', 'showoff', 'quantity', 'price'] 
+0

あなたのフォームは何ですか? – e4c5

+0

投稿を更新しました –

答えて

1

フォームが有効な場合にのみモデルを保存します。これはあなたのフォームです

class ProductForm(ModelForm): 
    class Meta: 
     model = Product 
     fields = ['photo', 'showoff', 'quantity', 'price'] 

4つのフィールドがあります。しかし、あなたのシミュレートされたフォームのポストは、それに

data = dict(showoff='showoff 33333',) 

#Preparing to post to the Update url 
url = reverse('wadiyabi:product_update', kwargs={'pk': product.pk}) 
request = RequestFactory().post(url, data=data) 

を一つだけのフィールドを持っているので、フォームが有効になるだろうことはありません。その結果、モデルは決して保存されません。したがって結果。