RSpec example group naming for webapps
This question is about how to best name RSpec example groups and examples in English.
I understand that in RSpec, describe
, context
(which are functionally equivalent) and it
are supposed to give you complete sentences. So for example,
describe "Log-in controller" do
context "with logged-in user" do
it "redirects to root" do
开发者_如何学JAVA...
end
end
end
reads Log-in controller with logged-in user redirects to root
. Awesome.
But in my application, where I need to test all components on an ajaxy page (using Capybara), I tend to have example groups like this:
describe "blog post" do
describe "content" do
it "is displayed"
end
describe "comment" do
it "is displayed"
describe "editing" do
it "works" # successful comment editing
it "requires logged-in user" # error case 1
it "requires non-empty body" # error case 2
end
end
describe "comment form" do
it "works" # successful comment submission
it "requires valid email address" # error case 1
it "requires non-empty body" # error case 2
end
end
I see two anti-patterns here:
The nested describes don't read as sentences. Of course one could put an 's:
describe "blog post" do describe "'s content" do it "is displayed" end end
Or one could put a colon after "blog post:". Or ideally, I would write
describe "blog post" do its "content" do it "is displayed" end end
but that's not possible because
its
is about attribute access, and I just have strings here.Is there a better way to deal with the "page components" problem?
For the functionality, the successful cases (for functionality like comment submission) are simply marked as
it "works"
. At least this is concise and simple -- I find it slightly preferable toit "can be submitted and causes a comment to be added"
, because that just forces me to make up verbiage for something that is obvious. But is there a nicer, more "natural" way to do this?
Suggestions for how to restructure the example example-group ;) above would be appreciated!
You shouldn't really think about having examples be grammatically correct. It's fine if your test reads 'blog post content is displayed' without the 's. The test is readable and simple. What you really want is to be able to understand what is failing when a test doesn't work.
With regards to your second point, 'it works' is usually not descriptive enough. It doesn't let someone else know what you mean by 'works'. If you are actually testing many things it's best to split your examples up, for instance:
describe 'blog post' do context 'creating a comment' do it 'should require a logged-in user' it 'should require a non-empty body' it 'should require a valid email address' it 'should create a new comment' it 'should be submittable' end end
精彩评论