public
Last active

Thoughts about RSpec for Python

  • Download Gist
blocks.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# codec: blocks
 
describe('articles.views.ArticleView'):
 
context('when user has permissions'):
 
it('should add new article'):
# some code
 
it('should delete existing article'):
# some code
 
context('when user has no permissions'):
it('should not add new article')
it('should not even show article form')
tests.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
from bdd import describe, context, it
 
 
with describe('articles.views.ArticleView'):
 
with context('when user has permissions'):
 
@it('should add new article')
def test():
# some code
 
@it('should delete existing article')
def test():
# some code
 
with context('when user has no permissions'):
# pending tests
it('should not add new article')
it('should not even show article form')

How about creating a DSL with its own parser that generates and runs python code. Most python syntax highlight and auto-completion tools can work fine with it (bonus).

For example:

import spec_helper

describe articles.views.ArticleView
    context 'a user with permissions':
        it 'should add a new article':
            # some code
        it 'should delete an existing article':
            # some code
    context 'a user without permissions':
        it 'should not add a new article'
        it 'should not show the article form'

Then RSpec matchers can usually be translated into unittest2 assertions.
http://rubydoc.info/gems/rspec-expectations/RSpec/Matchers

Python unittest2 assertions are not really much more verbose than the .should and .should_not rspec helpers, but more pythonic:

assert expected is False
assert expected is None
assert expected is not None
assert isinstance(expected, list)
assert almost_equal(expected, 55)

As I don't like all those parenthesis (), signs like @, keywords like with and def in the original gist. And RSpec just can't be written as native Python, so no reason to force it - there are other ways.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.