スタッフ ユーザーが下書き状態のオブジェクトを表示できるビューが必要です。しかし、このビューの単体テストを書くのは難しいと思います。
セットアップにFactory Boyを使用しています:
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
username = factory.LazyAttribute(lambda t: random_string())
password = factory.PostGenerationMethodCall('set_password', 'mysecret')
email = fuzzy.FuzzyText(
length=12, suffix='@email.com').fuzz().lower()
is_staff = True
is_active = True
class ReleaseFactory(factory.django.DjangoModelFactory):
class Meta:
model = Release
headline = factory.LazyAttribute(lambda t: random_string())
slug = factory.LazyAttribute(lambda t: slugify(t.headline))
author = factory.LazyAttribute(lambda t: random_string())
excerpt = factory.LazyAttribute(lambda t: random_string())
body = factory.LazyAttribute(lambda t: random_string())
class TestReleaseViews(TestCase):
"""
Ensure our view returns a list of :model:`news.Release` objects.
"""
def setUp(self):
self.client = Client()
self.user = UserFactory.create()
self.client.login(username=self.user.username, password=self.user.password)
テスト用にログインしたスタッフ ユーザーがいる場合、それを使用してビュー (404 ではなく status_code 200) をテストするにはどうすればよいですか?
たとえば、このテストは失敗します (404 != 200) 私のビューでis_staff
True を持つユーザーがビューにアクセスできる場合:
def test_staff_can_view_draft_releases(self):
"ReleaseDetail view should return correct status code"
release = ReleaseFactory.create(status='draft')
response = self.client.get(
reverse(
'news:release_detail',
kwargs={
'year': release.created.strftime('%Y'),
'month': release.created.strftime('%b').lower(),
'day': release.created.strftime('%d'),
'slug': release.slug
}
)
)
self.assertEqual(response.status_code, 200)