Rspec 如何组织测试用例?

Rails项目中,如何有效的组织测试用例? 个人的一些经验总结在此。

1. 可读性和可维护性是最重要的。

2. 层级和逻辑一定要清楚。

3. context 和 describe 描述一定要清晰. 基本的结构是

describe 测试什么类 do 
   describe 测试什么方法 do 
      context "测试的一个方面" do 
          it "它应该有什么样的表现" do 
          end
      end
   end
end
4. 一段比较好的测试用例代码示例
describe UsersController do
  describe "#create" do
    subject { post :create, :group_id => group_id, :user => attributes }
 
    let(:group_id) { mock(‘group_id’) }
    let(:group)    { mock(‘group’) }
    let(:user)     { mock(‘user’) }
 
    before do
      Group.should_receive(:find).with(group_id).and_return(group)
      group.should_receive(:create_user).with(attributes).and_return(users)
    end
 
    context ‘when attributes are valid’ do
      it ‘saves the user and redirects to the index page’ do
        user.should_receive(:persisted?).and_return(true)
        subject.should redirect_to(:users)
      end
    end
 
    context ‘when attributes are not valid’ do
      it ‘saves the user and redirects to the index page’ do
        user.should_receive(:persisted?).and_return(false)
        subject.should render_template(:new)
      end
    end
  end
end

Ref From: http://blog.codeship.io/2013/12/16/yes-you-should-write-controller-tests.html?utm_source=rubyweekly&utm_medium=email

1, 使用describe 和  context 来区分 不同的测试分类和同一个测试的不同方面

describe 一般用作分类,需要测试什么东西

context 用来对需要测试的东西的不同方面

比如

descirbe Order do #分类
   describe "#status" do 
      context "should include a default value" do  #具体的某一方面
         ... ...
     end 
   end
end

可以参考的文章 http://www.slideshare.net/ihower/rspec-7394497 @ihower的ppt,讲得非常详细,需要翻墙。

2, 区分类方法和实例方法

如 类方法用 .class_method, 实例方法使用 #instance_method 


3, 最好嵌套超过三层测试用例结构

比如 如下的测试代码看起来就非常清楚

describe ClassA do 
    describe "#method_a" do 
        context "x = 1" do 
         end
    end
end

4, 遇到多种交错的测试条件 改怎么办?

比如 我们要测试方法 method_a , 然后 方法 method_a 中有method_b 的条件约束 改怎么办呢?

可以使用Mock method_b方法,这样就能减少method_a 对method_b的依赖

describe ClassA do 

   describe "#method_a" do 
      before(:each) do 
         ClassA.should_recieve(:method_b).and_return(true)
      end
   end

   describe "#method_b" do 

   end
end



5,  在使用 factory_gril initialize一个对象的时候,尽量使用build,如代码

Factory.create(:name)

name = Factory.build(:name)
name.save(:validate_false)
name


6, 设置好 rspec的配置文件,能有利于我们查看spec的输出

#.rspec

--colour
--format d
--drb



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值