Reputation: 6114
I have a helper method defined in my RSpec spec which creates an instance of the class Dog
. But the spec is not able to recognize the method call dog.good_dog
.
helpers_demo_spec.rb
class Dog
attr_reader :good_dog, :has_been_walked
def initialize(good_or_not)
@good_dog = good_or_not
@has_been_walked = false
end
def walk_dog
@has_been_walked = true
end
end
describe Dog do
# helper method
def create_and_walk_dog(good_or_bad)
Dog.new(good_or_bad).walk_dog
end
it 'should be able to create and walk a good dog' do
dog = create_and_walk_dog(true)
expect(dog.good_dog).to be true
expect(dog.has_been_walked).to be true
end
end
Error Log:
C:\nital\my-data\my-sample-apps\Rails-Samples\rspec-samples\lib>rspec spec\helpers_demo_spec.rb
F
Failures:
1) Dog should be able to create and walk a good dog
Failure/Error: expect(dog.good_dog).to be true
NoMethodError:
undefined method `good_dog' for true:TrueClass
# ./spec/helpers_demo_spec.rb:26:in `block (2 levels) in <top (required)>'
Finished in 0.001 seconds (files took 0.33463 seconds to load)
1 example, 1 failure
Failed examples:
rspec ./spec/helpers_demo_spec.rb:24 # Dog should be able to create and walk a good dog
Upvotes: 2
Views: 1175
Reputation: 20033
The RSpec way of achieving what you want to do is to use blocks such as subject, let, before, after, etc.
describe Dog do
context 'good dog' do
subject { Dog.new(true) }
before(:each) do
subject.walk
end
it 'should be a good dog' do
expect(subject.good_dog).to be true
end
it 'should be a walked dog' do
expect(subject.has_been_walked).to be true
end
end
end
Upvotes: 3
Reputation: 711
Your helper method returns either a TrueClass
or a FalseClass
while your spec expects a Dog
instance. Your helper methods needs to return a Dog
instance. You should update your code to look like this:
def create_and_walk_dog(good_or_bad)
dog = Dog.new(good_or_bad)
dog.walk_dog
dog
end
Upvotes: 3
Reputation: 10416
def create_and_walk_dog(good_or_bad)
Dog.new(good_or_bad).walk_dog
end
You don't want walk_dog to be called here. It returns true, which gives you your error.
def create_and_walk_dog(good_or_bad)
Dog.new(good_or_bad)
end
Upvotes: 0