0

I am needing to achieve 100% code coverage for this class.

How would I test the following class in simplecov?

How can I test the save_user method in rspec?

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 
Max Copley
  • 430
  • 3
  • 15

1 Answers1

0

There are a couple of issues going on:

has_one :user
belongs_to :user

It's unusual to have both a 'has_one' and 'belongs_to' relation to referring to the same model. Usually you only need one or the other. (For instance, if Log has a user_id field, then you only need the belongs_to and not the has_one)

self.user_id = :current_user

You probably want current_user instead of :current_user, if you're trying to call a method rather than store a symbol.

To test that the after_save actually runs, I'd recommend something like:

log = Log.new
expect(log).to receive(:after_save).and_call_original
log.save
expect(log.user).to eq(current_user)

Calling save on a new instance will trigger the after_create to run, then you can verify the result and check that it ran correctly.

gmcnaughton
  • 2,233
  • 1
  • 21
  • 28