用Rspec测试“关联”的正确方法?

时间:2013-03-30 21:47:33

标签: ruby-on-rails rspec associations

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

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

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

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属性设为可访问(质量分配)。

5 个答案:

答案 0 :(得分:59)

我通常使用这种方法:

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

答案 1 :(得分:25)

  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) }

答案 2 :(得分:0)

你可以这样做最简单的方法。

it { expect(classroom).to have_many(:students) }
it { expect(user).to have_one(:profile }

一个有用的链接供参考。 https://gist.github.com/kyletcarlson/6234923

答案 3 :(得分:0)

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

答案 4 :(得分:0)

RSpec 是一个 ruby​​ 测试框架,而不是一个 Rails 框架。 own_to 是一个 rails 构造,而不是一个 ruby​​ 构造。 像 shoulda-matchers 这样的 Gems 将 ruby​​ 和 rails 连接起来,并帮助您编写好的测试。

牢记上述内容并遵循官方文档,应该可以帮助您了解最新信息并了解您所写的内容。

所以,下面是我要写的。

用户模型:

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

团队模型:

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