#261 Testing JavaScript with Jasmine (revised)
The jasminerice gem makes it easy to test your JavaScript with Jasmine in a Rails application. Here I also cover jasmine-jquery and guard-jasmine.
- Download:
- source codeProject Files in Zip (58.5 KB)
- mp4Full Size H.264 Video (31.2 MB)
- m4vSmaller H.264 Video (15.3 MB)
- webmFull Size VP8 Video (16.4 MB)
- ogvFull Size Theora Video (37.2 MB)
Resources
- Jasmine
- jasminerice
- jasmine-jquery
- guard-jasmine
- Episode 257: Request Specs with Capybara
- Episode 264: Guard
terminal
mkdir -p spec/javascripts brew install phantomjs guard init jasmine
Gemfile
group :development, :test do gem 'jasminerice' gem 'guard-jasmine' end
spec/javascripts/spec.js.coffee
#= require jquery #= require credit_card #= require_tree .
spec/javascripts/credit_card_spec.js.coffee
describe "CreditCard", -> it "strips out spaces and dashes from number", -> card = new CreditCard("1 2-3") expect(card.number).toBe("123") it "validates number using mod 10", -> validCard = new CreditCard("4111-1111-1111 1111") invalidCard = new CreditCard("4111111111111112") expect(validCard.validNumber()).toBeTruthy() expect(invalidCard.validNumber()).toBeFalsy() it "validates number when field loses focus", -> loadFixtures "order_form" field = $('#card_number') field.validateCreditCardNumber() field.val('123') field.blur() expect(field.next('.error')).toHaveText("Invalid card number.") field.val('4111-1111-1111 1111') field.blur() expect(field.next('.error')).toHaveText("")
app/assets/javascripts/credit_card.js.coffee
class @CreditCard constructor: (number) -> @number = number.replace(/[ -]/g, '') validNumber: -> total = 0 for i in [(@number.length-1)..0] n = +@number[i] if (i+@number.length) % 2 == 0 n = if n*2 > 9 then n*2 - 9 else n*2 total += n total % 10 == 0 $.fn.validateCreditCardNumber = -> @each -> $(this).blur -> card = new CreditCard(@value) if !card.validNumber() $(this).next('.error').text("Invalid card number.") else $(this).next('.error').text("")
app/assets/javascripts/orders.js.coffee
jQuery -> $('#order_card_number').validateCreditCardNumber()