Rspecでテスト書くときメモ

Rspecでテストを書く時、次のようにして書きます。
前はshouldを使っていたのをexpectを使って書く。
とその前にまずはrspecで書かれたテストコードを生成。


rails g rspec:model user

で生成されたspec/model/user_spec.rbの中身を修正。


1 require 'spec_helper'
2
3 describe User do
4 fixtures :users
5
6 describe "create_with_omniauth method test" do
7 context "first login by omniauth normal test" do
8 before do
9 auth = { provider: 'twitter' , uid: 'aabbbcc11111' }
10 @user = User.create_twitter_account auth
11 end
12
13 it "login success?" do
14 expect(@user).not_to be_nil
15 end
16
17 it "test attribute check" do
18 expect(@user.provider).to eql('twitter')
19 expect(@user.uid).to eql('aabbbcc11111')
20 end
21 end
22
23 context "second login by omniauth test" do
24 before do
25 auth = { provider: 'twitter' , uid: 'aabbcc112233' }
26 @user = User.create_twitter_account auth
27 end
28
29 it "login success? " do
30 expect(@user).not_to be_nil
31 end
32
33 it "attribute check" do
34 expect(@user.provider).to eql('twitter')
35 expect(@user.uid).to eql('aabbcc112233')
36 expect(@user.name).to be_nil
37 end
38 end
39 end
40 end

matcherも色々あります。

例えばエラーチェックのテスト


74 describe "group save test" do
75 context "group save error check" do
76 before do
77 end
78 it "save test" do
79 @group = Group.new
80 expect(@group).not_to be_valid
81 expect(@group).to have(1).errors_on(:name)
82 end
83 end
84 end

他にあるので、随時追加していく

その他matcher

  1. be_true
  2. be_within(2).of(1)
  3. be >=

rubyrspec