Search code examples
ruby-on-railstestingfixturesacts-as-taggable-on

Creating fixture data for model using acts_as_taggable_on


I'm using the acts_as_taggable_on plugin to provide tagging for my Framework model. I've got the functional tests that Rails generates, as well as the fixtures it uses and I would like to expand them to add some tags so that I can test searching by tag, etc.

Do I have to create fixtures for the taggings and tag tables and load them at the top of my functional tests? If so, how do I do that? I haven't gotten my head around the syntax for relations described here. Would an alternative be to grab a Framework instance and add the tags to it before testing the searching behavior? Or will the Rails gods strike me down if I do that?


Solution

  • It's generally best to create these kinds of things on the fly as you need them. Fixtures can quickly become pretty unmanageable, and when you look at the test in the future you will need to look at three or four fixture files to unpick what is happening.

    I'd recommend taking a little time out to look at the factory_girl gem, it will save you loads of time in the future. You'd do something like this:

    # test/factories.rb
    Factory.define :framework do |f|
      # Add any properties to make a valid Framework instance here, i.e. if you have
      # validates_presence_of :name on the Framework model ...
      f.name 'Test Name'
    end
    

    Then in your functional or unit tests you can easily create objects with the specific properties you need for an individual test:

    # Create and save in the DB with default values
    @framework = Factory.create(:framework)
    # Build an object with a different name and don't save it in the DB
    @framework = Factory.build(:framework, :name => 'Other name'
    # Create with tags
    @framework = Factory.build(:framework, :tags_list => 'foo, bar')