2013年3月20日水曜日

今更ながらRSpecを褒め称えてみる

例えば、こんなのが実行可能な単体テストだったりするんだぜ!
# Array spec
describe Array, "[1,2,3]" do
  subject { [1,2,3] }
  it {should be_an_instance_of(Array)}
  its(:size) {should == 3}
  it "should respond to :sort" do
    should respond_to(:sort)
  end
end
例外捕捉だってこんなにスマート
require "timeout"
describe Timeout, "timeout" do
  it "should raise TimeoutError if time is over" do
    lambda {
      Timeout.timeout(0.1) {sleep 0.2}
      }.should raise_error(TimeoutError)
  end

  it "should not raise TimeoutError unless time is over" do
    lambda {
      Timeout.timeout(0.1) {sleep 0.05}
      }.should_not raise_error
  end
end
stubやmockで任意のメソッドの結果を置き換えられるから、 時間や通信や外部IOなどがあるテストも簡単さ!
def is_over_limit
  Time.now > Time.utc(2100,1,1)
end

describe "is_over_limit" do
  it "should return false if before limit" do
    is_over_limit.should be_false
  end

  it "should return true if after limit" do
    Time.stub(:now => Time.utc(2100,1,1,0,0,1)) # Time.now が Time.utc(2100,1,1,0,0,1) を返すようになる
    is_over_limit.should == true
  end
end
"-fs" Optionを付けて実行すると、本当に仕様書みたいな感じなるんだ!
% rspec -fs
Array [1,2,3]
  should be an instance of Array
  should respond to :sort
  size
    should == 3

Timeout timeout
  should raise TimeoutError if time is over
  should not raise TimeoutError unless time is over

is_over_limit
  should return false if before limit
  should return true if after limit

Finished in 0.16024 seconds
7 examples, 0 failures


他、rspecのいいところ

  • テストを書き始めるまでが簡単。xUnitにありがちな念仏が一切要らない。これは実際とても有り難い。 
  • テストRunnerもとても賢い。まあ、rspec とだけ打てば大抵OKだ。あと、Rakefileに組み込むのも1行書くだけでOK。
  • タイプ量が少なくて済む。テストって意外と異様な行数になりがちだが、テストコード*量*を減らしつつ可読性を上げられる。可読性が高いことの価値は計り知れないよ。 
  • 特殊な文法に見えるが、Ruby言語なので自由に色々書くことができる。

RSpecの手始めはやはりこれを読むと良いのではないでしょうか。

やはりこの RSpec には夢があるッ!!」ですよ。

2013年3月14日木曜日

rubyのaws-sdkでEMRのリージョン指定

ドキュメントに書いてなくてわからなかったが、:emr_endpoint を指定しておけば良かったようだ。 こんな感じで好きなリージョンにEMRコマンドを発行できるようになります。
require "rubygems"
require "aws"
require "json"

credentials = JSON.load(File.read(opts[:credentials])) 
AWS.config({
    :access_key_id => credentials["access_id"], 
    :secret_access_key => credentials["private_key"], 
    :emr_key_pair => credentials["keypair"], 
    :emr_key_pair_file => credentials["key-pair-file"],
    :region => credentials["region"],
    :emr_endpoint => "#{credentials["region"]}.elasticmapreduce.amazonaws.com",
})
emr = AWS::EMR.new
puts emr.jobs.to_a

2013年3月13日水曜日

MacのQuickTime Playerでスロー再生する

MacのQuickTime Playerでは、動画の再生時にOptionキーを押しながら早送りボタンをクリックすると1.1倍、1.2倍、、、と次第に速くすることができるが、この方法だとゆっくり再生させることができないようだ。

だた、AppleScriptを使うと簡単にできるらしい。
下記のスクリプトを「AppleScriptエディタ」を起動して貼り付けて「実行」すると、
0.5倍速で再生される。何気に便利である。

tell application "QuickTime Player"
  set rate of document 1 to 0.5
end tell