【发布时间】:2016-04-19 20:58:16
【问题描述】:
我已将我的 Foos 控制器的一部分提取到一个新的 rails 模型中以执行该操作:
foos_controller.rb
class FoosController < ApplicationController
respond_to :js
def create
@foo = current_user.do_something(@bar)
actioned_bar = ActionedBar.new(@bar)
actioned_bar.create
respond_with @bar
end
actioned_bar.rb
class ActionedBar
def initialize(bar)
@bar = bar
end
def create
if @bar.check?
# do something
end
end
end
我先让它工作,但现在我正在尝试回填 rspec 控制器测试。
我将测试各种模型方法,并将进行功能测试以确保从该角度来看没问题,但我想添加一个测试以确保从 foos 控制器调用新的 actioned_bar 模型与@bar。
我知道在 rspec 中你可以测试一些 receives 一些 with 一些 arguments 但我正在努力让它工作。
it "calls ActionedBar.new(bar)" do
bar = create(:bar)
expect(ActionedBar).to receive(:new)
xhr :post, :create, bar_id: bar.id
end
这不起作用,控制台报告:
NoMethodError:
undefined method `create' for nil:NilClass
这很奇怪,因为它只在我使用 expect(ActionedBar).to receive(:new) 时才这样做,其余的控制器测试工作正常。
如果我尝试这样做:
it "calls ActionedBar.new(bar)" do
bar = create(:bar)
actioned_bar = ActionedBar.new(bar)
expect(actioned_bar).to receive(:create).with(no_args)
xhr :post, :create, bar_id: bar.id
end
控制台说:
(#<ActionedBar:0xc8f9f74>).create(no args)
expected: 1 time with no arguments
received: 0 times with no arguments
如果我在运行测试时在控制器中执行put;由于某种原因,此测试导致控制器中的 actioned_bar 输出为nil,但对于所有其他控制器测试都很好。
有什么方法可以测试此控制器规范中是否调用了 ActionedBar?
【问题讨论】:
标签: ruby-on-rails rspec controller