4

I have a spec like the following:

describe 'toggle_approval' do
  before(:each) do
    @comment = Comment.make(id: 55, approved: false)
  end

  it "toggles the visibility of the discussion" do
    post :toggle_approval, id: 55
    #@comment.reload
    @comment.approved.should be_true
  end
end

This spec will fail unless I uncomment the line that reloads the comment. Why is rails not reloading this for me?

2
  • It's simple. Do not use instance variable. Use let instead. Commented Mar 3, 2014 at 9:22
  • There is no let in rspec 1 Commented Mar 3, 2014 at 9:26

2 Answers 2

5

Because you don't tell it to reload your record. Comment instance in your controller is created independently from @comment variable set in your specs. So if you don't use reload explicitly, it won't be reloaded. If you want your Comment instance in controller to be the same instance than in spec, you can do some stubbing:

Comment.should_receive(:find).with(@comment.id) { @comment }
Sign up to request clarification or add additional context in comments.

Comments

1

To add to Marek's answer, you can also call .reload inline like so:

it "toggles the visibility of the discussion" do
  post :toggle_approval, id: 55
  @comment.reload.approved.should be_true
end

or use something like this:

it "toggles the visibility of the discussion" do
  expect {
    post :toggle_approval, id: 55
  }.to change {
    @comment.reload.approved
  }.from(...)
   .to(...)
end

Comments

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.