Skip to content

Instantly share code, notes, and snippets.

@dnagir
Created October 22, 2011 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnagir/1305824 to your computer and use it in GitHub Desktop.
Save dnagir/1305824 to your computer and use it in GitHub Desktop.
Users
should save record when losing focus from input
Expected spy updateFromForm to have been called.
Error: Expected spy updateFromForm to have been called.
class App.Users extends Spine.Controller
elements:
'form': 'form'
# Events are bound via Proxy, so you can't spy on them. We have to wrap actual handler in a dummy method to spy on those.
events:
'blur input': 'onBlur'
constructor: ->
super
@render()
render: ->
@html @generate @template, @model
onBlur: -> @updateFromForm()
updateFromForm: ->
@model.updateAttributes @form.serializeForm()
describe "Users", ->
users = null
user = null
input = -> $(".users input[name='name']")
beforeEach ->
setFixtures "<div class='users' />"
user = new App.User(name: 'Dima', email: 'me@example.com', summary: 'Summary')
users = new App.Users(el: '.users', template: 'edit', model: user)
spyOn user, 'save'
# This passes
it "should udpate record with form data", ->
input().val('Jimmy')
users.updateFromForm()
expect(user.name).toBe 'Jimmy'
expect(user.save).toHaveBeenCalled()
# This fails, I can't see why the 'blur' is not triggered
# The blur is, however, triggered when I manually bind it:
# users.el.delegate 'input', 'blur', -> console.warn('Bluurrrred!')
it "should save record when losing focus from input", ->
spyOn users, 'updateFromForm'
input().trigger('blur')
expect(users.updateFromForm).toHaveBeenCalled()
@maccman
Copy link

maccman commented Oct 22, 2011

It's because the spy is being called in the wrong context. Also, you should never be using '.init' - always use 'new'. Have a look at Spine's model tests for a way to proxy the spy context.

@dnagir
Copy link
Author

dnagir commented Oct 22, 2011

Ups. Using new now.

The spy is set on users instance (in the spec) as well as on user instance (in the beforeEach block). So the spy is set-up correctly. Or I am missing something?

@dnagir
Copy link
Author

dnagir commented Oct 22, 2011

@maccman, the weird thing is that when I manually users.el.delegate, it does work. So the event is triggers successfully and handled.
I must be missing something stupid when defining it with Spine.

@dnagir
Copy link
Author

dnagir commented Oct 23, 2011

@maccman, you're right. When updateFromForm is called as event handler - it is proxied, so that the actual function is hidden and can't be replaces (spied on).
The only way to avoid that - is to make a dummy function onBlur for event handlers and call the actual function from there.

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