Rails + Rspec:它/描述/上下文描述的模式和样式?

时间:2013-10-16 18:13:01

标签: ruby-on-rails rspec

我知道这与实际的代码本身并没有关系,但我只是从Rspec开始,我在测试听起来像英语时遇到了麻烦。我认为,如果我理解了要传递给它的字符串中的内容并描述块,它会大大提高我的测试质量。例如:

    Category
      validations
        is valid with a title and description
        is invalid without a title
        is invalid without a description
      when it has subcategories
        returns the right children subcategories
        should be accessible by its subcategories
      when it has no subcategories
        returns an empty set

这是我的类别规范中出现的内容。是否有某种方式/模式我必须编写传递给itdescribe的字符串?对于Rspec专家,当您编写describe字符串时,您通常会想到什么?这与您编写it字符串或context字符串时有何不同?以下是我需要一些实际代码的规范示例:

  describe 'validations' do
    let(:category) { Category.new }
    it 'is valid with a title and description' do
      category.title = 'Category'
      category.description = 'Lorem Ipsum'
      category.should be_valid
    end

    it 'is invalid without a title' do
      category.description = 'Lorem Ipsum'
      category.should_not be_valid
    end

    it 'is invalid without a description' do
      category.title = 'Category'
      category.should_not be_valid
    end

  end

  context 'when it has subcategories' do
    let(:category) { FactoryGirl.create(:category) }
    it 'returns the right children subcategories' do
      child = category.subcategories.build(title: 'Child Category', description: 'Lorem Ipsum')
      category.subcategories.should include(child)
    end

    it 'should be accessible by its subcategories' do
      child = category.subcategories.build(title: 'Child Category', description: 'Lorem Ipsum')
      child.parent_category.should_not be_nil
    end
  end

  context 'when it has no subcategories' do
    let(:category) { FactoryGirl.create(:category) }
    it 'returns an empty set' do
      category.subcategories.should be_empty
    end
  end

2 个答案:

答案 0 :(得分:2)

基本上:

  • describe用于“某事”。 “Something”可以是实例或类方法,也可以是功能规范中的操作。如果是类方法则为“.method_name”,如果是实例方法则为“#method_name”。
  • context用于描述spec的特殊情况(context是describe的别名)。通常以“when”开头。
  • it就是'某事'。通常以“should”开头。

describe ".to_s"
  context "when is a number"
    it "convert the number in a string"
  context "when is a string"
    it "return the same object"

但这并不严格。这是一个指导:

答案 1 :(得分:0)

我通常以should开始我的测试用例。因此,您的测试运行将具有类似

的内容
Category
      validations
        should be valid with a title and description
        should be invalid without a title
        should be invalid without a description
      with subcategories
        should return the right children subcategories
        should be accessible by its subcategories
      without subcategories
        should return an empty set

我发现如上所述更容易理解功能。