2

这是我的代码工作但我的测试失败并且我需要知道我做错了什么的情况之一?

我有一个项目类,它的all方法只是吐出这个类的实例:

class Project

    @@all_projects = []

    def initialize(options)
      @@all_projects << self
    end

    def self.all
    @@all_projects
  end
end

现在Project.all工作得很好,但我写的规范没有。

context "manipulating projects" do
    before do
        options1 = {
            name: 'Building house'
        }

        options2 = {
            name: 'Getting a loan from the Bank'
        }

        @project1 = Project.new(options1)
        @project2 = Project.new(options2)
    end
        it "can print all projects" do
      Project.all.should eq([@project1, @project2])
    end

我收到的失败消息是:

Project manipulating projects can print all projects
     Failure/Error: Project.all.should eq([@project1, @project2])

       expected: [Building house, Getting a loan from the Bank]
            got: [Building house, Building house, Building house, Getting a loan from the Bank, Building house, Getting a loan from the Bank]

这是要点中的完整规范:https ://gist.github.com/4535863

我究竟做错了什么?我该如何解决?

4

2 回答 2

3

它使结果加倍,因为它为每个before测试运行块,其中修改了类属性(当初始化两个新项目时),并且(根据要点)您所指的测试是第二个。

为避免该问题,您需要@@all_projects在 after 块中重置:

after do
  Project.class_variable_set :@@all_projects, []
end

另请参阅:如何在 ruby​​ 中清除 rspec 测试之间的类变量

(感谢@iain将重置代码移动到after块而不是before块的建议。)

于 2013-01-15T03:51:09.610 回答
1

这不使用before块来设置臭名昭著的实例变量。

describe Project do
  let(:options1){ 
    {
      name: 'Building house',
      priority: 2,
      tasks: []
    }
  }
  let(:options2) {
    {
      name: 'Getting a loan from the Bank',
      priority: 3,
      tasks: []
    }
  }
  let(:project1) { Project.new(options1) }
  let(:project2) { Project.new(options2) }

  context "while starting up" do

    subject { Project.new options1 }
    its(:name) { should include('Building house') }

    its(:tasks) { should be_empty }
  end

  context "manipulating projects" do
    before :all do
      Project.all.clear
    end

    subject { Project.all }
    its(:count) { should be > 0 }

    it { should eq [project1, project2] }

  end

end
于 2013-01-15T04:25:16.070 回答