一,安装ruby。
二,运行命令,安装rspec的gem包:
1 |
gem install rspec |
会看到如下的结果:
Fetching: rspec-core-2.14.7.gem (100%) Fetching: diff-lcs-1.2.5.gem (100%) Fetching: rspec-expectations-2.14.5.gem (100%) Fetching: rspec-mocks-2.14.6.gem (100%) Fetching: rspec-2.14.1.gem (100%) Successfully installed rspec-core-2.14.7 Successfully installed diff-lcs-1.2.5 Successfully installed rspec-expectations-2.14.5 Successfully installed rspec-mocks-2.14.6 Successfully installed rspec-2.14.1 5 gems installed
三,在纯ruby环境中使用rspec。
1,新建一个文件夹,随意命名为my_test。
2,在my_test下新建一个lib文件夹,lib文件夹下新建一个rb文件,例如bowling.rb。
3,在my_test下新建一个测试文件,命名为bowling_spec.rb,文件名一定要以_spec结尾。
4,在bowling.rb中写入如下代码:
# bowling.rb class Bowling def hit(pins) end def score 0 end end
5,在为bowling_spec.rb中写入如下测试代码:
# bowling_spec.rb require ‘bowling‘ describe Bowling, "#score" do it "returns 0 for all gutter game" do bowling = Bowling.new 20.times { bowling.hit(0) } bowling.score.should eq(0) end end
6,运行命令,进行测试:
$ rspec bowling_spec.rb --format nested Bowling#score returns 0 for all gutter game Finished in 0.007534 seconds 1 example, 0 failures
四,rails中使用rspec。
1,安装gem包,运行命令:
gem install rspec-rails
会看到如下的结果:
Fetching: i18n-0.6.9.gem (100%) Fetching: minitest-4.7.5.gem (100%) Fetching: atomic-1.1.14.gem (100%) Temporarily enhancing PATH to include DevKit... Building native extensions. This could take a while... Fetching: thread_safe-0.1.3.gem (100%) Fetching: activesupport-4.0.3.gem (100%) Fetching: builder-3.1.4.gem (100%) Fetching: rack-1.5.2.gem (100%) Fetching: actionpack-4.0.3.gem (100%) Fetching: rspec-rails-2.14.1.gem (100%) Successfully installed i18n-0.6.9 Successfully installed minitest-4.7.5 Successfully installed atomic-1.1.14 Successfully installed thread_safe-0.1.3 Successfully installed activesupport-4.0.3 Successfully installed builder-3.1.4 Successfully installed rack-1.5.2 Successfully installed actionpack-4.0.3 Successfully installed rspec-rails-2.14.1 9 gems installed
2,创建一个rails工程,进入工程目录,执行如下命令:
rails generate rspec:install
如果提示:Could not find generator rspec:install.
请看http://www.nujk.com/could-not-find-generator-rspec-install
这个时候,就会创建了spec的文件夹。
原文:http://www.cnblogs.com/fanxiaopeng/p/3563772.html