This is one of those cases where my code is working but my test is failing and I need to know what I am doing wrong?
I have a Project class with an all method that just spits out instances of this class:
class Project
@@all_projects = []
def initialize(options)
@@all_projects << self
end
def self.all
@@all_projects
end
end
Now Project.all works just fine but the spec I am writing doesn’t.
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
The failure message I get is:
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]
Here is the full spec in a gist: https://gist.github.com/4535863
What am I doing wrong? How can I fix it?
It is doubling the results because it runs the
beforeblock for each test, where the class attribute is modified (when two new projects are initialized), and (according to the gist) the test you’re referring to is the second one.To avoid the problem you’ll need to reset
@@all_projectsin an after block:See also: How can I clear class variables between rspec tests in ruby
(Thanks to @iain for the suggestion to move the reset code to an
afterblock rather than abeforeblock.)