我已经在SO上查看了几个问题,无法找到我正在寻找的内容。
我有一个简单的rails控制器。使用新方法和私有方法:
class FooController < ApplicationController
before_action :load_bar
def new
@foo = @bar.foos.build
end
private
def load_bar
@bar = Bar.find params[:bar_id]
end
end
如何正确测试新方法,我应该测试load_bar方法吗?我目前正在做以下事情,但感觉不是很正确:
describe FooController do
let(:bar) { create(:bar) }
context 'GET new' do
let(:foo) { mock_model(Foo) }
it 'should assign a @foo' do
Bar.should_receive(:find).and_return(bar)
bar.stub_chain(:foos, :build).and_return(foo)
get :new, bar_id: bar
assigns(:foo).should == foo
end
end
end
答案 0 :(得分:0)
这样的事情足以测试这个动作:
describe FooController do
describe "GET 'new'" do
let(:bar) { create :bar }
it "assigns bar" do
get :new, bar_id: bar.to_param # Or bar.id
expect(assigns[:bar]).to eq(bar)
end
it "assigns a new foo" do
get :new, bar_id: bar.to_param
expect(assigns[:foo]).to be_a_new(Foo)
end
end
end