[英]simplecov class test example
我需要實現此類的100%代碼覆蓋率。
我將如何在simplecov中測試以下課程?
如何在rspec中測試save_user方法?
class Log < ActiveRecord::Base
has_and_belongs_to_many :tags
has_one :asset
has_one :user
belongs_to :user
after_create :save_user
def save_user
self.user_id = :current_user
self.save()
end
end
describe Log do
context "When saving a user is should save to the database."
it "should call insert fields with appropriate arguments" do
expect(subject).to receive(:asset).with("TestData")
expect(subject).to receive(:user).with("DummyName")
expect(subject).to save_user
subject.foo
end
end
發生了兩個問題:
has_one :user
belongs_to :user
同時具有“ has_one”和“ belongs_to”關系來引用同一模型是不尋常的。 通常,您只需要一個。 (例如,如果Log有一個user_id字段,那么您只需要belongs_to
而不是has_one
)
self.user_id = :current_user
如果您嘗試調用方法而不是存儲符號,則可能需要current_user
而不是:current_user
。
要測試after_save
實際運行,我建議使用類似以下的內容:
log = Log.new
expect(log).to receive(:after_save).and_call_original
log.save
expect(log.user).to eq(current_user)
在新實例上調用save將觸發after_create
運行,然后您可以驗證結果並檢查其是否正確運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.