With this helper, doesn’t @mock_account only get set once inside its
‘describe’ block? Any future tests would use the same @mock_account,
even if
other stubs were designated.
def mock_person(stubs={}) @person ||= mock_model(Person, stubs)
end
describe “GET” do
before(:each) do
mock_person(:name => "fred")
end
it "should have name fred" do
@person.name.should == "fred"
end
it "should have name steve" do
mock_person(:name => "steve")
@person.name.should == "steve"
end
end
describe “POST” do
it "should have name steve" do
mock_person(:name => "steve")
@person.name.should == "steve"
end
it "should have name bob" do
mock_person(:name => "bob")
@person.name.should == "bob"
end
end
end
‘PersonController GET should have name steve’ FAILED
expected: “steve”,
got: “fred” (using ==)
./spec/controllers/person_controller_spec.rb:21:
end
got: “fred” (using ==)
./spec/controllers/person_controller_spec.rb:21:
Finished in 0.295898 seconds
6 examples, 1 failure
Admittedly, this is a violation of the principal of least surprise,
but your analysis of the problem is not quite accurate.
Each example is run in its own instance of the group (just like xUnit
frameworks) and has its own state. before(:each) gets run, as it says,
before each example in the context of its own instance of the group.
So what’s happening is that the mock_person(:name => “fred”) in the
before is creating the instance, whereas the mock_person(:name =>
“steve”) in the example is not actually creating a new object - it
essentially does nothing
I think that the mock_person method probably needs to be smarter so if
it’s already been called AND it gets args it raises an error. WDYT?
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.