在.net世界中,我的规范将遵循排列、动作、断言模式。我在rspec中复制它时遇到了问题,因为在SUT采取行动后,似乎没有能力选择性地验证您的mock。这一点,再加上在每个'It‘代码块的末尾都会对每个期望进行评估的事实,导致我在很多规范中重复自己。
下面是我正在讨论的一个例子:
describe 'AmazonImporter' do
before(:each) do
Kernel.**stubs**(:sleep).with(1)
end
# iterates through the amazon categories, and for each one, loads ideas with
# the right response group, upserting ideas as it goes
# then goes through, and fleshes out all of the ideas that only have asins.
describe "find_new_ideas" do
before(:all) do
@xml = File.open(File.expand_path('../amazon_ideas_in_category.xml', __FILE__), 'r') {|f| f.read }
end
before(:each) do
@category = AmazonCategory.new(:name => "name", :amazon_id => 1036682)
@response = Amazon::Ecs::Response.new(@xml)
@response_group = "MostGifted"
@asin = 'B002EL2WQI'
@request_hash = {:operation => "BrowseNodeLookup", :browse_node_id => @category.amazon_id,
:response_group => @response_group}
Amazon::Ecs.**expects**(:send_request).with(has_entries(@request_hash)).returns(@response)
GiftIdea.expects(:first).with(has_entries({:site_key => @asin})).returns(nil)
GiftIdea.any_instance.expects(:save)
end
it "sleeps for 1 second after each amazon request" do
Kernel.**expects**(:sleep).with(1)
AmazonImporter.new.find_new_ideas(@category, @response_group)
end
it "loads the ideas for the given response group from amazon" do
Amazon::Ecs.**expects**(:send_request).
with(has_entries(@request_hash)).
returns(@response)
**AmazonImporter.new.find_new_ideas(@category, @response_group)**
end
it "tries to load those ideas from repository" do
GiftIdea.expects(:first).with(has_entries({:site_key => @asin}))
**AmazonImporter.new.find_new_ideas(@category, @response_group)**
end在这个部分示例中,我测试了find_new_ideas方法。但我必须为每个规范调用它(完整的规范有9个断言块)。我还必须复制mock设置,以便它在之前的块中被截断,但在it/assertion块中是单独期望的。我在这里复制或几乎复制了一大堆代码。有没有更好的办法让我看不见?
(SUT =被测系统。不确定这是不是每个人都这么叫,或者仅仅是alt.net的人)
发布于 2010-08-07 01:48:58
您可以使用共享示例组来减少重复:
shared_examples_for "any pizza" do
it "tastes really good" do
@pizza.should taste_really_good
end
it "is available by the slice" do
@pizza.should be_available_by_the_slice
end
end
describe "New York style thin crust pizza" do
before(:each) do
@pizza = Pizza.new(:region => 'New York' , :style => 'thin crust' )
end
it_behaves_like "any pizza"
it "has a really great sauce" do
@pizza.should have_a_really_great_sauce
end
end另一种技术是使用宏,如果您在不同的类中需要类似的规范,这是很方便的。
注意:上面的例子借用自The RSpec Book,第12章。
发布于 2010-08-06 19:34:30
你可以使用"context“将它们分开,如果这有帮助的话...
https://stackoverflow.com/questions/3421268
复制相似问题