Skip to content

Instantly share code, notes, and snippets.

@garybernhardt
Created November 23, 2011 21:48
Show Gist options
  • Save garybernhardt/1390018 to your computer and use it in GitHub Desktop.
Save garybernhardt/1390018 to your computer and use it in GitHub Desktop.
# Make a user that we'll add a book to.
user = User.create!
controller.stub(:current_user) { user }
# This prints []. The book list is empty.
p user.books
# Expect a book to be added to the user. This fails (see below)
expect {
post :create, :id => asin
}.to change { user.books }.from([]).to([book])
# Failure/Error: expect {
# books should have initially been [], but was [#<Book id: 1, asin: "the-asin", title: "Hamlet", authors: "Bill Shakes", pages: 0, is_ebook: false, image_url: nil, icon_url: nil, details_url: "http://example.com/hamlet", created_at: "2011-11-23 21:47:45", updated_at: "2011-11-23 21:47:45", editorial_review: nil>]
# This seems wrong. `user.books` *is* initially []. Help? I'm running RSpec 2.7.1 on Ruby 1.8.7 and Rails 3.0.9. It also happens with RSpec 2.5.
@dchelimsky
Copy link

user.books returns the same object both times, and that object gets updated in place :(

@garybernhardt
Copy link
Author

But RSpec contains a special case to dup Enumerables, and user.books.is_a?(Enumerable) is true, though the when/case match in RSpec isn't firing for some reason. This is hurting my brain.

@dchelimsky
Copy link

Oh - I forgot we added that :(

Regardless, this should work: }.to change{ user.books.first }.from(nil).to(book)

@garybernhardt
Copy link
Author

Ahh, yes! That's much less confusing than a manual dup. Thanks.

@dchelimsky
Copy link

It's not as nice as what you had originally, but it's a fair trade-off to get it to work.

@justinko
Copy link

I think change { user.books.reload }.from([]).to([book]) works too. But yuck.

@garybernhardt
Copy link
Author

Nope, reloading the books doesn't help (neither does reloading the user). duping the books does. Confusingly, to_aing the books doesn't (I'd expect it to create a new array each time).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment