Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing rails' nested attributes with rspec

I'm pretty new to testing and rails and tried to figure it out myself but without any luck.

I have the following models

class Picture < ActiveRecord::Base
  belongs_to :product
  has_attached_file :image
end

class Product < ActiveRecord::Base
  has_many :pictures, :dependent => :destroy
  accepts_nested_attributes_for :pictures, :reject_if => lambda { |p| p[:image].blank? }, :allow_destroy => true
end

and a controller which is pretty standard, I guess…

def create
  @product = Product.new(params[:product])
  if @product.save
    redirect_to products_path, :notice => "blah."
  else
    render :action => "new"
  end
end

how would I go about and test this? i tried something like this but I can't get it to work:

describe ProductsController do
  it "adds given pictures to the product" do
    product = Factory.build(:product)
    product.pictures.build(Factory.attributes_for(:picture))
    post :create, :product => product.attributes
    Product.where(:name => product[:name]).first.pictures.count.should == 1 # or something
  end
end

It probably has something to do with the way the attributes are passed to the create action but how can I get this to work? Im using rails 3.1.rc5 but i doubt that that hast anything to do with why its not working…

or would you not test this at all since it is basic rails functionality and most likely well tested to begin with?

like image 879
maiwald Avatar asked Aug 12 '11 18:08

maiwald


2 Answers

Try:

post :create, :product => Factory.attributes_for(:product, :pictures => [ Factory.build(:picture) ])
like image 172
Steve Avatar answered Oct 17 '22 23:10

Steve


As you say you don't really need to test this, necessarily, because it will be covered by the basic rails functionality, and stuff like this should be thoroughly covered by your integration tests.

However if you DO want to test this the best way is tail your development logs and see what is being posted to the action, copy and paste that into your test and then modify it to suite your needs.

Using attributes or the factory_girl attributes isn't going to cut it unfortunately.

like image 35
jonnii Avatar answered Oct 18 '22 00:10

jonnii