[英]Mocks or factories in unit tests for a Rails controller?
我有一個帶有index
方法的DashboardController
,它通過以下幾行與我的User
模型進行交互:
def index
user = User.first
log_data = user.logs
# more controller code here that uses the log_data
end
我正在為此index
方法編寫控制器規格。 我為我的用戶模型定義了一個FactoryGirl工廠。 在這個單元測試,我應該嘲笑了user
這里有instance_double
某種,或我應該建立User
與FactoryGirl對象? 是否有關於如何測試控制器的約定/標准/傾向?
我要說的是,不必嘲笑用戶對象-它只會使您的規格離現實更遠。 您可以像這樣高興地設置規格:
describe DashboardController, :type => :controller do
let(:user) { create(:user) }
describe "#index" do
it "your test here" do
####
end
end
end
但是,在另一個訪問current_user
對象的實例中,您可能會嘗試利用以下內容:
let(:user) { create :user }
before do
allow(controller).to receive(:current_user).and_return(user)
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.