【问题标题】:rspec 'allow' stub isn't setting variablesrspec 'allow' 存根未设置变量
【发布时间】:2015-08-13 19:37:15
【问题描述】:

我有一个控制器功能:

def update
    @simulation = Simulation.find(params[:id])
    @simulation.next
    puts "--"
    puts @simulation.dirty?
    puts @simulation.save

    if (@simulation.save && @simulation.dirty?)
        render :partial => 'show', :object => @simulation
    end
end

还有一个 rspec 测试:

    it "should render a partial when the record is dirty" do 
        allow(@simulation).to receive('dirty?') { true }

        put :update, :id => @simulation.id, :format => 'js'

        expect(response).to render_template( :partial => 'show' )
    end

测试未能呈现视图,因为 if 检查没有通过,因为它不会为 @simulation#dirty 返回 true?即使函数被存根。由于控制器中的放置,我可以看到这一点。任何想法为什么它不起作用?

【问题讨论】:

    标签: ruby-on-rails rspec controller stub


    【解决方案1】:

    你正在存根的实例变量@simulation不属于控制器实例,而是属于rspec测试用例类实例。在允许方法调用之后,在 rspec 的 it 块中尝试@simulation.dirty?。我猜它返回true。但是,控制器中的 @simulation 没有被存根。它们是两个不同的对象。

    如果你想在控制器的更新方法中存根@simulation,你应该存根模拟类的所有实例。尝试使用 allow_any_instance_of 而不是 allow(@simulation)。

    allow_any_instance_of(Simulation).to receive(:dirty?).and_return(true)
    

    https://github.com/rspec/rspec-mocks#settings-mocks-or-stubs-on-any-instance-of-a-class

    【讨论】:

    • 这给了我NoMethodError: undefined method ancestors' for #<0x007fd0d1925a50>
    • <0x007fd0d1925a50>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    • 2013-05-26
    • 1970-01-01
    相关资源
    最近更新 更多