RSpec best practices and tips #翻译

原文:http://eggsonbread.com/2010/03/28/my-rspec-best-practices-and-tips/

1. 用简写specify{}/it{}/subject{}

it "should be valid" do
  @user.should be_valid
end
可以写成这样:
specify { @user.should be_valid }


还可以这样写
describe User do
  it { should validate_presence_of :name }
  it { should have_one :address }
end


引入subject来给定一个默认的subject
subject { @user.address }
it { should be_valid }
2.开头描述:context :“when/with"
方法 : #
没有节操的写法最后输出:
User non confirmed confirm email wrong token should not be valid
按上面写法后(不用去研究英语语法了):
User when non confirmed when #confirm_email with wrong token should not be valid

 3.Rspec matchers 出错能更明确些:
如果我们用==
specify { user.valid?.should == true }
'User should == true' FAILED
expected: true,
got: false (using ==)


用be_valid matcher:
specify { user.should be_valid }
'User should be valid' FAILED
expected valid? to return true, got false


4. 不要在一个it里写多个expectation
这样写,错了你也不知道错在哪里:
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
end


这样错了,才知道是哪里有问题
describe DemoMan do
before(:all) do
  @demo_man = DemoMan.new
end
subject { @demo_man }
  it { should respond_to :name }
  it { should respond_to :gender }
  it { should respond_to :age }
end



5. 用descibe和context组织Spec
使用nested模式来看你的Spec组织好没有:
spec spec/my_spec.rb -cf nested


每个Context和Describe 下用Before来整理数据,并激活it{}(应该是before返回值当成默认)
describe User do
  before { @user = User.new }
 
  subject { @user }
 
  context "when name empty" do
    it { should not be_valid }
    specify { @user.save.should == false }
  end
 
  context "when name not empty" do
    before { @user.name = 'Sam' }
 
    it { should be_valid }
    specify { @user.save.should == true }
  end
 
  describe :present do
    subject { @user.present }
 
    context "when user is a W" do
      before { @user.gender = 'W' }
 
      it { should be_a Flower }
    end
 
    context "when user is a M" do
      before { @user.gender = 'M' }
 
      it { should be_an IMac }
    end
  end
end



6. 测试边界有效性
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
end

你可能感兴趣的:(Ruby,rspec)