RSpec shared examples with template methods

本文介绍了一种使用RSpec共享例子来减少重复测试代码的方法。通过模板方法模式,仅需实现拍卖路径这一模板方法,即可复用大部分测试逻辑,适用于在线拍卖和现场拍卖控制器的测试。

It’s pretty common to have multiple tests that are nearly the same.

In one app, we support bidding on both online and hammer auctions (auctions with people physically present). They’re separate controllers but with a lot of shared code and behavior.

We want to test both, but we’d rather not write two almost identical tests if we can help it.

So we’ve been using RSpec shared examples, with the template method patternto account for the differences, and we like it.

Here’s a simplified example:

spec/request/online_bidding_spec.rb

1
2
3
4
5
6 7 8 9 10 11 12
require "spec_helper" require "support/shared_examples/bidding"  describe "Bidding online" do  include_examples :bidding   let(:auction) { FactoryGirl.create(:online_auction) }   def auction_path  online_auction_path(auction)  end end 

spec/request/hammer_bidding_spec.rb

1
2
3
4
5
6 7 8 9 10 11 12
require "spec_helper" require "support/shared_examples/bidding"  describe "Bidding at hammer auction" do  include_examples :bidding   let(:auction) { FactoryGirl.create(:hammer_auction) }   def auction_path  hammer_auction_path(auction)  end end 

spec/support/shared_examples/bidding.rb

1
2
3
4
5
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
shared_examples :bidding do  it "lets you bid when logged in" do  log_in # Implemented somewhere else.  visit auction_path  place_bid  bid_should_be_accepted  end   it "doesn't let you bid when not logged in" do  visit item_path  place_bid  bid_should_be_rejected  end   def auction_path  raise "Implement me."  end   def place_bid  fill_in "Bid", with: 123  click_button "Place bid"  end   def bid_should_be_accepted  page.should have_content("OK! :)")  end   def bid_should_be_rejected  page.should have_content("NO! :(")  end end 

The only template method here is auction_path . The shared example makes sure, by raising, that it’s overridden in your concrete specs.

转载于:https://www.cnblogs.com/goody9807/p/5481354.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值