Method: Shoulda::ClassMethods#context
- Defined in:
- lib/shoulda/context.rb
#context(name, &blk) ⇒ Object
Contexts
A context block groups should statements under a common set of setup/teardown methods. Context blocks can be arbitrarily nested, and can do wonders for improving the maintainability and readability of your test code.
A context block can contain setup, should, should_eventually, and teardown blocks.
class UserTest < Test::Unit::TestCase
context "A User instance" do
setup do
@user = User.find(:first)
end
should "return its full name"
assert_equal 'John Doe', @user.full_name
end
end
end
This code will produce the method "test: A User instance should return its full name. "
.
Contexts may be nested. Nested contexts run their setup blocks from out to in before each should statement. They then run their teardown blocks from in to out after each should statement.
class UserTest < Test::Unit::TestCase
context "A User instance" do
setup do
@user = User.find(:first)
end
should "return its full name"
assert_equal 'John Doe', @user.full_name
end
context "with a profile" do
setup do
@user.profile = Profile.find(:first)
end
should "return true when sent :has_profile?"
assert @user.has_profile?
end
end
end
end
This code will produce the following methods
-
"test: A User instance should return its full name. "
-
"test: A User instance with a profile should return true when sent :has_profile?. "
Just like should statements, a context block can exist next to normal def test_the_old_way; end
tests. This means you do not have to fully commit to the context/should syntax in a test file.
165 166 167 168 169 170 171 172 |
# File 'lib/shoulda/context.rb', line 165 def context(name, &blk) if Shoulda.current_context Shoulda.current_context.context(name, &blk) else context = Shoulda::Context.new(name, self, &blk) context.build end end |