2015-07-05 65 views
0

我的rspec测试vote__spec.rb指出我的up_votes方法未定义,但它在列出的votes.rb文件中列出。任何人都可以指导我为什么说它是未定义的?Rspec测试无法在模型文件中找到方法

Rspec的错误

2) Vote validations value validation only allows -1 or 1 as values 
Failure/Error: expect(@votes.up_votes).where(value: [1,-1]) 
NoMethodError: 
    undefined method `up_votes' for nil:NilClass 
# ./spec/models/vote_spec.rb:5:in `block (4 levels) in <top (required)>' 

投票Rspec的

describe Vote do 
describe "validations" do 
    describe "value validation" do 
    it "only allows -1 or 1 as values" do 
    expect(@post.up_votes).where(value: [1,-1]) 
    end 
end 
end 
end 

Vote.rb文件

class Vote < ActiveRecord::Base 
belongs_to :user 
belongs_to :post 

    def up_votes 
    votes.where(value: 1).count 
    end 

end 

回答

1

错误是出现贝科使用@post变量需要被初始化。一旦我初始化@post变量,如下所示,错误得到解决:

before do 
    @post = Post.create(title: 'Post title', body: 'Post bodies must be pretty long.') 
    3.times {@post.votes.create(value: 1)} 
    2.times {@post.votes.create(value: -1)} 
end