Правильный способ тестирования "ассоциаций" с Rspec?
Я пытаюсь протестировать следующий сценарий:
- > У меня есть модель под названием 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
Из-за меня меняет модель Team как:
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 attribute доступным (массовое присвоение).
Ответы
Ответ 1
Я обычно использую этот подход:
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
Ответ 2
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) }
Ответ 3
Вы можете простой способ сделать это, как.
it { expect(classroom).to have_many(:students) }
it { expect(user).to have_one(:profile }
полезная ссылка для справки. https://gist.github.com/kyletcarlson/6234923
Ответ 4
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