Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I test accepts_nested_attributes_for with Rspec Rails3

I have a model as follows:

class Greeting < ActiveRecord::Base

  attr_accessible :headline, :icon, :content

  belongs_to :user


  accepts_nested_attributes_for :user, :reject_if => proc { |a| a[:name].blank? || a[:email].blank? } 

How can I do an Rspec test for this?

like image 911
chell Avatar asked Jul 01 '11 04:07

chell


2 Answers

I just found this shoulda macro, seems like it works fine:

https://gist.github.com/1353500/bae9d4514737a5cd7fa7315338fdd9053dbff543

you should use it like this:

it{ should accept_nested_attributes_for :samples }
like image 59
joselo Avatar answered Nov 19 '22 17:11

joselo


Here you have Shoulda macro for testing accepts_nested_attributes_for: http://mediumexposure.com/testing-acceptsnestedattributesfor-shoulda-macros/. It does not support any options (such as :reject_if), only bare accepts_nested_attributes_for.

But for :reject_if, you can create a valid Greeting model with nested attributes for User but without :name. Then check if user has been saved, and then same with blank :email

So you can do something like this:

describe Greeting
  it { expect { Factory(:greeting, :user_attributes => Factory_attributes_for(:user)) }.to change(User, :count).by(1) }
  it { expect { Factory(:greeting, :user_attributes => Factory_attributes_for(:user, :name => '')) }.to_not change(User, :count) }
  it { expect { Factory(:greeting, :user_attributes => Factory.attributes_for(:user, :email => '')) }.to_not change(User, :count) }
end
like image 16
Szymon Przybył Avatar answered Nov 19 '22 18:11

Szymon Przybył