Created
October 29, 2009 18:19
-
-
Save kylefox/221668 to your computer and use it in GitHub Desktop.
Faster tests with Should & FactoryGirl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Very contrived example of how using class variables to hold expensive models/associations | |
# can drastically speed up tests when using Shoulda and FactoryGirl. | |
# | |
# One caveat is that your test cases are no longer truly isolated. That is, if your | |
# test case modifies one of the "cached" instances, subsequent test cases may be invalid. | |
# | |
# You should only store models as class variables if: | |
# 1) Your test cases do not modify their data, and | |
# 2) The data contained in the cached models isn't vital to your test case. | |
class TaskTest < ActiveSupport::TestCase | |
# NOTE: Previous versions of this gist had this chunk of code inside a `setup` block. Don't do that. Do this instead. | |
# Models that are expensive to create (lots of associations, callbacks, etc) | |
# and are not vital to the innards of the tests can be stored as class variables. | |
# This prevents them being created before *every single test case* | |
@@account ||= Factory(:account) | |
@@user ||= Factory(:user, :account => @@account) | |
@@project ||= Factory(:project, :account => @@account) | |
setup do | |
# If we weren't passing in @@project and @@user, these factories | |
# would create the Project and User associations internally, | |
# before every single test case. | |
@new_task = Factory(:task, :project => @@project, :assigned_to => @@user) | |
@completed_task = Factory(:task, :completed_at => Time.now, :project => @@project, :assigned_to => @@user) | |
end | |
context "A Task" do | |
should "know if it's been completed" do | |
assert !@new_task.completed? | |
assert @completed_task.completed? | |
end | |
should "know that a completed task is not blocking it" do | |
assert !@new_task.is_blocked_by(@completed_task) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment