2011-07-01 71 views
12

我有一个模型,如下所示:如何测试accepts_nested_attributes_for使用RSpec Rails3中

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? } 

我怎样才能做一个Rspec的测试呢?

回答

12

这里您有Shoulda用于测试的宏accepts_nested_attributes_forhttp://mediumexposure.com/testing-acceptsnestedattributesfor-shoulda-macros/。它不支持任何选项(如:reject_if),仅支持accepts_nested_attributes_for

但是对于:reject_if,您可以创建一个有效的Greeting模型,其嵌套属性为User,但不包含:name。然后检查用户是否已被保存,然后用空白:email

一样的,所以你可以做这样的事情:

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