Skip to content

Instantly share code, notes, and snippets.

@jferris
Created July 5, 2012 21:18
Show Gist options
  • Save jferris/3056522 to your computer and use it in GitHub Desktop.
Save jferris/3056522 to your computer and use it in GitHub Desktop.
it 'finds posts containing the given word in the title' do
# The titles are in a different file than the test, so you need to flip back and forth to see
# what's actually going on here. When somebody adds another example post to the fixtures, this
# test will start failing, which is a distraction and a waste of time. We were also never able to
# come up with fixtures that weren't either hopelessly entangled or completely bloated from adding
# a specific fixture for almost every test.
Post.search('example').map(&:title).should =~ ['example one', 'example two']
end
it 'finds posts containing the given word in the title' do
# This test has exactly the data you're talking about right in the test, and none of the data is
# tangled up with the setup for other tests. New tests will have their own data from factories and
# won't cause this test to fail.
create(:post, title: 'example one')
create(:post, title: 'example two')
create(:post, title: 'other post')
Post.search('example').map(&:title).should =~ ['example one', 'example two']
end
@jacobo
Copy link

jacobo commented Jul 5, 2012

why not just?

Post.create!(:title => "example one")

@dchelimsky
Copy link

@jacobo that's perfectly fine until a requirement comes in that Post.validates_presence_of :author. Now, not only do you have to go to every example with Post.create!(:title => "something") and change it, but you have to add data to each example this is not relevant to the example:

it 'finds posts containing the given word in the title' do
  author = Person.create!(:username => "jacobo")
  Post.create!(:author => author, :title => "example one")
  Post.create!(:author => author, :title => "example two")
  Post.create!(:author => author, :title => "other post")
  Post.search('example').map(&:title).should =~ ['example one', 'example two']
end

The author in that example is pure noise.

With a factory method (tool supported or hand-rolled) you would only need to change this in one place, and the example would stay focused on the data that is relevant to the example (as in the 2nd example in the gist).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment