0
我有User
,Account
和Role
模型。用戶可以自己存在。帳戶必須通過角色綁定到用戶。帳戶必須至少有一個「所有者」類型的角色記錄。我不確定如何在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中看起來會是什麼樣子。
此測試失敗(數組回來空):
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的是什麼。
工廠:通過用諷刺框架"mock"其他對象依賴於其他對象
FactoryGirl.define do
factory :user do
name "Mickey Mouse"
email "[email protected]"
password "m1ckey"
password_confirmation "m1ckey"
end
factory :account do
title "ACME Corporation"
subdomain "acme"
end
factory :role do
user
account
end
end
或者他可以使用RSpec內置的[mocks](https://github.com/rspec/rspec-mocks)。 –
@MarkThomas,太棒了!另一件要學習的東西。我只能找到一種在RoR中提高生產力的方法。總有一些新東西需要學習。 RSpec,水豚,嘲笑,存根(stub),咖啡劇本,sass,名單永不止息! – Mohamad
@MarkThomas:是的,這在我鏈接的IBM文檔中提到。 –