48

我正在尝试测试以下场景:

-> 我有一个名为 Team 的模型,当它由用户创建时才有意义。因此,每个 Team 实例都必须与一个 User 相关联。

为了测试这一点,我做了以下事情:

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

这迫使我将团队模型更改为:

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

这对你来说是否正确?我只是担心将 :user 属性设置为可访问(批量分配)。

4

4 回答 4

68

我通常使用这种方法:

describe User do
  it "should have many teams" do
    t = User.reflect_on_association(:teams)
    expect(t.macro).to eq(:has_many)
  end
end

更好的解决方案是使用 gem shoulda,它可以让您简单地:

describe Team do
  it { should belong_to(:user) }
end
于 2013-03-30T21:52:35.373 回答
26
  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) }
于 2014-04-30T14:56:59.760 回答
1
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
于 2019-07-16T22:08:59.120 回答
0

RSpec is a ruby test framework, and not a rails framework. belongs_to is a rails construct, and not a ruby construct. Gems like shoulda-matchers connect ruby and rails things and help you write good tests.

Having the above in mind and following official documentation, should help you stay up to date and understand what you are writing.

So, below is what I would write.

User model:

RSpec.describe User, type: :model do
  context 'associations' do
    it { should have_many(:teams).class_name('Team') }
  end
end

Team model:

RSpec.describe Team, type: :model do
  context 'associations' do
    it { should belong_to(:user).class_name('User') }
  end
end
于 2020-12-25T12:27:22.247 回答