2014-03-03 22 views
3

我有类似下面的规格:为什么我必须重新加载rspec规范中的实例变量?

describe 'toggle_approval' do 
    before(:each) do 
    @comment = Comment.make(id: 55, approved: false) 
    end 

    it "toggles the visibility of the discussion" do 
    post :toggle_approval, id: 55 
    #@comment.reload 
    @comment.approved.should be_true 
    end 
end 

,除非我取消重新加载注释的行此规范将失败。为什么rails没有为我重新加载?

+0

这很简单。不要使用实例变量。改用'let'。 – Hauleth

+0

rspec 1中没有'let' – railsuser400

回答

5

因为你不告诉它重新加载你的记录。您的控制器中的Comment实例独立于您的规格中的@comment变量集创建。所以如果你不明确地使用reload,它将不会被重新加载。如果你想在控制器的Comment实例比在规格相同的情况下,你可以做一些磕碰:

Comment.should_receive(:find).with(@comment.id) { @comment } 
1

为了增加鸡马立克氏回答,你也可以拨打.reload内嵌像这样:

it "toggles the visibility of the discussion" do 
    post :toggle_approval, id: 55 
    @comment.reload.approved.should be_true 
end 

或使用类似如下:

it "toggles the visibility of the discussion" do 
    expect { 
    post :toggle_approval, id: 55 
    }.to change { 
    @comment.reload.approved 
    }.from(...) 
    .to(...) 
end 
相关问题