测试&QUOT的正确途径;关联"使用RSpec? [英] Correct way of testing "associations" with Rspec?
本文介绍了测试&QUOT的正确途径;关联"使用RSpec?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想测试以下情形:
- >我有一个叫团队模式,是很有道理的时候就已经由用户创建的。因此,每个队的实例已被相关的用户
-> I have a model called Team which it just makes sense when it has been created by a User. Therefore, each Team instance has to be related to a User.
为了测试这一点,我已经做了以下内容:
In order to test that, I have done the following:
describe Team do
...
it "should be associated with a user" do
no_user_team = Team.new(:user => nil)
no_user_team.should_not be_valid
end
...
end
这迫使我改变球队模型
为:
Which forces me to change the Team model as:
class Team < ActiveRecord::Base
# Setup accessible (or protected) attributes for your model
attr_accessible :name, :user
validates_presence_of :name
validates_presence_of :user
belongs_to :user
end
这看起来正确的吗?我只是担心做出的:用户属性的访问(质量分配)。
Does this seem correct to you? I am just worried of make the :user attribute as accessible (mass assignment).
推荐答案
我通常使用这种方法:
describe User do
it "should have many teams" do
t = User.reflect_on_association(:teams)
t.macro.should == :has_many
end
end
有一个更好的解决办法是使用宝石早该这将让您只需:
A better solution would be to use the gem shoulda which will allow you to simply:
describe Team do
it { should belong_to(:user) }
end
这篇关于测试&QUOT的正确途径;关联&QUOT;使用RSpec?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文