my_first_spec.csand put the following code in it:
>NSpecRunner.exe YourClassLibraryName\bin\debug\YourClassLibraryName.dll my first spec asserts at the method level describe nesting asserts in a method more nesting also asserts in a lambda
If you’ve used any of the following testing frameworks, you’ll feel right at home with NSpec:
In NSpec, there is no need for access modifiers on tests, and no need to decorate test methods with attributes.
For example, this NUnit/XUnit test:
Would be written like this in NSpec (notice that there are no access modifiers or attributes):
You can nest a lambda within a method (you can defer inheritance hierarchies):
Here is an NSpec test that has nested structures:
Here is what you’d have to write the test above in NUnit/XUnit. It’s gross and poopy. Specifically:
Lets take a look at some features of NSpec.
NSpec has some simple assertions, but you should really just use FluentAssertions. You can build your own assertions by using extention methods. For example:
Want to do some setup before tests are run? Use
before. The state of
the class is reset with each test case (side effects/mutations don’t spill over).
Test hierarchies are communicated through the
context keyword. If a
method contains underscores, then it will be picked up by NSpec. Any
method that starts with
specify_ will be treated as just a
simple NUnit/XUnit style test case.
You can ignore tests by preceding any structure with an
x. Or you can
todo keyword provided by NSpec.
Title cased (conventional C#) methods are ignored my NSpec.
Here’s a fancy feature. Sometimes, what is done to a class remains the
same, but the setup varies. You can use
act. Each nested
context will execute
act before assertions are run.
Being able to nest tests is awesome. But you’ll can always use inheritance to “flatten” tests if needed.
All test structures are supported at the class level too. Here is how
you’d write a
it/specify at the class level.
If you want to hook into the debugger quickly. Just place the
following line inside of your tests. When you run
the debugger will pop right up:
NSpec also includes
DebuggerShim.cs when you install it via Nuget. So you can use TDD.NET/ReSharper to run your tests.
Or you can do something even fancier, and build your own console
app! Instead of creating a Class Library for the test project,
create a Console Project. Add the following code in
Then you can debug everything like you would any other program. More importantly, creating your own console app gives you the power to tailor input and output to your liking using NSpecs’s API/constructs.