More testing with Paperclip, rspec, factory girl and associations

Testing associations with Rspec is not as difficult as it first appears, although when combining with Paperclip uploads it adds some challenges.

In this case we have an ingredient that belongs to a foodgroup and the ingredient has an attached paperclip image.

Controller Tests

Add foodgroup_id = 1 to the valid_attributes definition in the ingredients_controller_spec.rb

def valid_attributes
{
  :name => "Test Ingredient",
  :description => "Test Description",
  :history => "A long long time ago",
  :image => fixture_file_upload('spec/fixtures/images/test.jpg', 'image/jpeg'),
  :foodgroup_id => 1
}
end

This should allow the

post :create, :ingredient => valid_attributes

tests to pass.

For tests that require a valid associated item e.g. in this case a valid foodgroup is needed to save the ingredient, we can use a Factory to replace

ingredient = Ingredient.create! valid_attributes

with

ingredient = Factory.create(:ingredient)

In factories.rb you'll need to have something similar to

Factory.define :foodgroup do |foodgroup|
  foodgroup.name         "Test Foodgroup"
  foodgroup.description  "Test Description"
  foodgroup.image        Rack::Test::UploadedFile.new('spec/fixtures/images/test.jpg', 'image/jpeg')
end

Factory.define :ingredient do |ingredient|
  ingredient.name         "Test Ingredient"
  ingredient.description  "Test Description"
  ingredient.history      "A long long time ago"
  ingredient.image        Rack::Test::UploadedFile.new('spec/fixtures/images/test.jpg', 'image/jpeg')
  ingredient.association  :foodgroup, :factory => :foodgroup
end

One other note:

Factory.attributes_for

Does not return the associated id. You can use

Factory.build(:user).attributes.symbolize_keys 

Unfortunately this does not play well with the paperclip setup and does not provide the "image" field so using this method instead of valid_attributes does not work.

 

 

Post new comment

  • Syntax highlight code surrounded by the {syntaxhighlighter SPEC}...{/syntaxhighlighter} tags, where SPEC is a Syntaxhighlighter options string or "class="OPTIONS" title="the title".
  • Lines and paragraphs break automatically.

More information about formatting options