我的模型如下:
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测试?
答案 0 :(得分:24)
我刚刚发现这个应该是宏,看起来它运行正常:
https://gist.github.com/1353500/bae9d4514737a5cd7fa7315338fdd9053dbff543
你应该像这样使用它:
it{ should accept_nested_attributes_for :samples }
答案 1 :(得分:14)
您可以使用Shoulda
宏来测试accepts_nested_attributes_for
:http://mediumexposure.com/testing-acceptsnestedattributesfor-shoulda-macros/。它不支持任何选项(例如:reject_if
),只支持裸accepts_nested_attributes_for
。
但对于:reject_if
,您可以创建一个有效的问候语模型,其中包含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