如何在RSpec中使用辅助方法?

时间:2016-02-22 15:16:38

标签: ruby-on-rails ruby testing rspec

我有一个在我的RSpec规范中定义的辅助方法,它创建了类Dog的实例。但规范无法识别方法调用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

错误日志:

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

3 个答案:

答案 0 :(得分:3)

当您的规范需要TrueClass实例时,您的帮助方法会返回FalseClassDog。您的帮助程序方法需要返回Dog实例。您应该将代码更新为:

def create_and_walk_dog(good_or_bad)
  dog = Dog.new(good_or_bad)
  dog.walk_dog
  dog 
end 

答案 1 :(得分:2)

实现您想要做的事情的 RSpec方式是使用subjectletbeforeafter等块,等

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

答案 2 :(得分:1)

def create_and_walk_dog(good_or_bad)
  Dog.new(good_or_bad).walk_dog 
end 

你不希望在这里调用walk_dog。它返回true,这会给你错误。

def create_and_walk_dog(good_or_bad)
  Dog.new(good_or_bad)
end