thedanotto thedanotto - 5 months ago 17
Ruby Question

rails rspec testing updating attribute on model

I have a very simple model called

Reminder
with a boolean attribute of
verified
and I want to test my method
update_verified
which simply sets the attribute
verified
to
true
. I'm using rspec and factory girl.

# reminder.rb
def update_verified
self.update(verified: true)
end

# reminder_spec.rb
describe "#update_verified" do
it "should mark the reminder.verified to true" do
reminder = build(:reminder, verified: false)
reminder.update_verified

expect(reminder.verified).to eq(true)
end
end


For some reason, when I run the test, the new value of
true
for the attribute
verified
is not being persisted. However, when I run the method in console, it works fine. Thoughts?

1) Reminder#update_verified should mark the reminder.verified to true
Failure/Error: expect(reminder.verified).to eq(true)

expected: true
got: false

(compared using ==)
# ./spec/models/reminder_spec.rb:46:in `block (3 levels) in <top (required)>'

Finished in 0.19193 seconds (files took 7.07 seconds to load)

Answer

You need to call reload on object.
And please follow rspec best practices: use let and subject.

describe "#update_verified" do
  let(:reminder) { build(:reminder, verified: false) }
  subject { reminder.update_verified }
  it "should mark the reminder.verified to true" do
    subject
    expect(reminder.reload.verified).to eq(true)
  end
end

UPDATE
The problem is in build method. It creates new object and does not save object to DB.
Replace build with create method.