1

我知道这与实际代码本身并没有真正的关系,但我刚刚开始使用 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

这就是我的类别规范中的内容。是否有某种方式/模式我必须编写传递给itand的字符串describe?对于您的 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
4

2 回答 2

2

基本上:

  • describe是为了“某事”。“某事”可以是实例或类方法,也可以是功能规范中的操作。如果是类方法,则为“.method_name”,如果是实例方法,则为“#method_name”。
  • context 用于描述规范的特殊情况(上下文是 的别名describe)。通常以“何时”开头。
  • it是什么做'某事'。通常以“应该”开头。

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"

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

于 2013-10-16T18:46:35.077 回答
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

我发现像上面那样更容易理解功能。

于 2013-10-16T18:23:31.780 回答