对于Rspec,从刚开始的抵触到现在的喜欢。
写了一年多的Rspec 了, 下面就总结下一些比较好的写法。
1. 在赋值的时候,使用let() {}
Before
describe Array do
before (:each) do
@array = Array.new
end
context "create a new array" do
it "should be empty" do
@array.should be_empty
end
end
endAfter
describe Array do
let(:array) { Array.new }
context "create a new array" do
it "should be empty" do
array.should be_empty
end
end
end
2. 当你需要mock 某个函数的时候,不要使用let 使用before do,这样程序看起来更舒服,清晰
describe Array do
let(:array) { Array.new }
before do
User.should_receive(:post).and_return("hello")
end
context "" do
end
end3. 尽量不要使用before(:all) do
4. 使用before do 默认就是before(:each) do
5. 对于class函数前面加"#", 对于instance函数前面加"."
describe Array do
describe "#pop" do
end
describe ".test" do
end
end6. 描述函数 和class module 的时候,使用describe, 描述具体的test case 使用context
这样可以使得测试流程更为清晰
describe Array do
describe "#pop" do
context "no data in Array" do
end
context "only one data in Array" do
end
context "more than one data in Array" do
end
end
end7. test case 中一定要测有效值,边界值和无效值以及nil
describe "#month_in_english(month_id)" do
context "when valid" do
it "should return 'January' for 1" # lower boundary
it "should return 'March' for 3"
it "should return 'December' for 12" # upper boundary
context "when invalid" do
it "should return nil for 0"
it "should return nil for 13"
end
end8.一个it block 只测试一个期待值
Bad
describe DemoMan do
it "should have expected attributes" do
demo_man = DemoMan.new
demo_man.should respond_to :name
demo_man.should respond_to :gender
demo_man.should respond_to :age
end
endGood
describe DemoMan do
let(:demo_man) { DemoMan.new }
subject { demo_man }
it { should respond_to :name }
it { should respond_to :gender }
it { should respond_to :age }
end
本文详细介绍了RSpec测试框架的高效使用技巧,包括赋值方式、mock函数、避免before(:all)等最佳实践,以及如何清晰地组织测试用例和描述函数、类的方法。通过实例演示了如何编写更易读、更清晰的RSpec测试代码,旨在帮助开发者提升测试效率和代码质量。
2859

被折叠的 条评论
为什么被折叠?



