0

In the below spec, I want to test that for a Notification instance, running the destructive method #mark_as_dismissed will change the has_been_read column to true. How do you do that while keeping the test nice and terse?

context "#mark_as_dismissed" do
  subject { create(:notification) }
  subject.mark_as_dismissed # How do I specify this
  its(:has_been_read) { should be_true }
end

1 Answer 1

3

There's multiple ways to write tests and different preferred syntaxes, so this is quite an opinionated answer.

Following your style, it would look more like this:

describe "#mark_as_dismissed" do
  subject { create(:notification) }
  before { subject.mark_as_dissmissed }

  its(:has_been_read) { should be_true }
end

Mine would be more like this:

describe "#mark_as_dismissed" do
  let(:notification) { create(:notification) }

  it "marks the notification as read" do
    notification.mark_as_dissmissed
    notification.has_been_read.should be_true
  end
end

syntatic sugar: Rspec allows a special syntax for methods returning booleans. I would have to test it, I am not sure it would work in this case but perhaps you can do something like:

# for the first alternative
it { should have_been_read }

# for the second alternative
it "marks the notification as read" do
  notification.mark_as_dissmissed
  notification.should have_been_read
end

Bonus points To remove the db dependency you can just 'build' the notification instead of using 'create' (which persists the model in the database). If the #mark_as_dismissed method does not need the db (can do a non persistent update), then the test should still work.

build(:notification) # instead of create(:notification)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Bonus points for showing how to remove DB dependency for this spec.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.