Testing nested rails attributes with rspec

I am new to testing and rails and tried to figure it out myself, but with no 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 that is pretty standard, I think ...

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 do and check? 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

This is probably due to 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 this has anything to do with why it doesn't work ...

or would you not test it at all, since these are the basic functions of the rails and, most likely, are well tested for a start?

+5
source share
2 answers

, , , , .

, , - , , , , .

factory_girl, , .

+5

Try:

post :create, :product => Factory.attributes_for(:product, :pictures => [ Factory.build(:picture) ])
+5

All Articles