ホーム > 今日のテストコード > Google Chart APIを使ってQRコードを生成する

Google Chart APIを使ってQRコードを生成する

QRコードの生成にGoogle Chart APIを使ってみました。
rspec-railsのhave_tagマッチャを使うときはassert_selectのドキュメントを見ながらの場合が多いですね。早く覚えてしまいたい。
tech-memo
app/helpers/chart_helper.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
module ChartHelper
 
  def qr_code_tag(text, options = {})
    param = { 
      :cht => 'qr',
      :chl => text
    }
    param[:chs] = options.delete(:chart_size) || '120x120'
    uri = URI::HTTP.build(:host => 'chart.apis.google.com', :path => '/chart', :query => param.to_query)
 
    image_tag uri.to_s, options
  end
 
end

spec/helpers/chart_helper_spec.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
require 'spec_helper'
 
describe ChartHelper do
 
  it '指定したテキストを含むQRコードを得られること' do
    tag = helper.qr_code_tag('http://tech.hapicky.com/')
    expected_src = 'http://chart.apis.google.com/chart?chl=http%3A%2F%2Ftech.hapicky.com%2F&chs=120x120&cht=qr'
    tag.should have_tag('img[src=?]', expected_src)
  end
 
  it 'サイズ指定できること' do
    tag = helper.qr_code_tag('http://tech.hapicky.com/', :chart_size => '300x300')
    expected_src = 'http://chart.apis.google.com/chart?chl=http%3A%2F%2Ftech.hapicky.com%2F&chs=300x300&cht=qr'
    tag.should have_tag('img[src=?]', expected_src)
  end
 
  it 'altの指定ができること' do
    tag = helper.qr_code_tag('http://tech.hapicky.com/', :alt => 'tech-memo')
    expected_src = 'http://chart.apis.google.com/chart?chl=http%3A%2F%2Ftech.hapicky.com%2F&chs=120x120&cht=qr'
    tag.should have_tag('img[src=?][alt=tech-memo]', expected_src)
  end
 
end

参考: