Ruby-on-rails 用 Rspec 测试“关联”的正确方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15723856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Correct way of testing "associations" with Rspec?
提问by Hommer Smith
I am trying to test the following scenario:
我正在尝试测试以下场景:
-> 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.
-> 我有一个名为 Team 的模型,当它由用户创建时才有意义。因此,每个 Team 实例都必须与一个 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).
这对你来说是正确的吗?我只是担心使 :user 属性可访问(批量分配)。
回答by Luís Ramalho
I usually use this approach:
我通常使用这种方法:
describe User do
it "should have many teams" do
t = User.reflect_on_association(:teams)
expect(t.macro).to eq(:has_many)
end
end
A better solution would be to use the gem shouldawhich will allow you to simply:
更好的解决方案是使用 gem shoulda,它可以让您简单地:
describe Team do
it { should belong_to(:user) }
end
回答by urbanczykd
it { Idea.reflect_on_association(:person).macro.should eq(:belongs_to) }
it { Idea.reflect_on_association(:company).macro.should eq(:belongs_to) }
it { Idea.reflect_on_association(:votes).macro.should eq(:has_many) }
回答by Aleem
You can you simplest way to do this like.
你可以用最简单的方法来做到这一点。
it { expect(classroom).to have_many(:students) }
it { expect(user).to have_one(:profile }
a useful link for reference. https://gist.github.com/kyletcarlson/6234923
回答by juliangonzalez
class MicroProxy < ActiveRecord::Base
has_many :servers
end
describe MicroProxy, type: :model do
it { expect(described_class.reflect_on_association(:servers).macro).to eq(:has_many) }
end

