che*_*ell 14 testing rspec2 ruby-on-rails-3
我有一个模型如下:
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? }
Run Code Online (Sandbox Code Playgroud)
我该如何为此进行Rspec测试?
jos*_*elo 27
我刚刚发现这个应该是宏,似乎它工作正常:
https://gist.github.com/1353500/bae9d4514737a5cd7fa7315338fdd9053dbff543
你应该像这样使用它:
it{ should accept_nested_attributes_for :samples }
Run Code Online (Sandbox Code Playgroud)
Szy*_*był 15
在这里你有Shoulda测试的宏accepts_nested_attributes_for:http://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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8659 次 |
| 最近记录: |