我有 User
、Account
和 Role
模型。用户可以单独存在。帐户必须通过角色绑定(bind)到用户。一个帐户必须至少有一个“所有者”类型的角色记录。我不确定如何在 RSpec 和 FactoryGirl 中测试它。
# user_id, account_id, role
Role < ActiveRecord::Base
belongs_to :user
belongs_to :account
end
User < ActiveRecord::Base
has_many :roles
has_many :accounts, through: roles
accepts_nested_properties_for :accounts
end
Account < ActiveRecord::Base
has_many :roles
has_many :users, through: roles
end
如果用户未登录,Accounts.new 将显示用户和帐户表单。如果用户已登录,则只会显示“帐户”表单。问题是,我不确定在尝试测试关联时 RSpec 中的 Role 和 Account 会是什么样子。
此测试失败(数组返回为空):
describe Account do
let(:user) { FactoryGirl.create(:user) }
before { @account = user.accounts.build(title: "ACME Corporation", subdomain: "acme") }
subject { @account }
it { should respond_to(:users) }
its(:users) { should include(user) }
然后,当用户登录时和未登录时,测试会更加复杂。我可以看到类似用例的任何引用示例代码吗?我也不确定要在 roles_spec 中测试什么,以及什么属于 accounts_spec/user_spec。
工厂:
FactoryGirl.define do
factory :user do
name "Mickey Mouse"
email "mickey@disney.com"
password "m1ckey"
password_confirmation "m1ckey"
end
factory :account do
title "ACME Corporation"
subdomain "acme"
end
factory :role do
user
account
end
end
最佳答案
您通过使用模拟框架来测试依赖于其他对象的对象 "mock"其他对象。有许多 mock frameworks允许您执行此操作。
关于ruby-on-rails - 您如何测试依赖于另一个模型的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10391184/