为什么我必须在rspec规范中重新加载实例变量?

rai*_*400 3 rspec ruby-on-rails

我的规格如下:

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
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*pka 5

因为您没有告诉它重新加载您的记录.Comment控制器中的实例是独立@comment于规范中设置的变量创建的.因此,如果您不reload明确使用,则不会重新加载.如果您希望Comment控制器中的实例与规范中的实例相同,则可以执行一些存根:

Comment.should_receive(:find).with(@comment.id) { @comment }
Run Code Online (Sandbox Code Playgroud)