0

このクラスのコード カバレッジを 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 
4

1 に答える 1

0

進行中の問題がいくつかあります。

has_one :user
belongs_to :user

同じモデルを参照するために「has_one」と「belongs_to」の両方の関係があるのは珍しいことです。通常、どちらか一方だけが必要です。(たとえば、ログに 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が実行され、結果を確認して正しく実行されたことを確認できます。

于 2016-09-27T04:58:21.050 に答える