我的控制器看起来像这样:
def index
params[:page]||1
@stories = Story.all.page(params[:page]).per(5)
end
当我尝试使用RSpec为链接线编写控制器测试时,我似乎无法通过测试。
我的controller_spec看起来像:
describe '#index' do
let(:story) {double(Story)}
before do
allow(Story).to receive(:all).and_return(story)
allow(story).to receive(:page).and_return(story)
allow(story).to receive(:per).and_return(story)
get :index
end
context 'when user is not logged in' do
it 'should get page 1' do
expect(story).to receive(:page).with(1)
end
it 'should get 5 stories' do
expect(story).to receive(:per).with(5)
end
end
end
为这样的控制器编写什么是好的示例测试?
答案 0 :(得分:1)
您应该在致电expect(story).to receive(:page).with(1)
get :index
将get :index
从before
块移至it
块:
it 'should get page 1' do
expect(story).to receive(:page).with(1)
get :index
end
PS,看起来您在控制器操作中错过了=
params[:page] ||= 1
答案 1 :(得分:1)
我认为你可以使用这样的东西:
def index
params[:page] ||= 1
@stories = Story.all.page(params[:page]).per(5)
end
describe '#index' do
let(:stories) { [double(Story)] }
let(:index) { -> { get :index, page: 1, pre: 5 } }
context 'when user is not logged in' do
it 'should get 5 last stories and assign to @stories' do
expect_any_instance_of(Story).to receive(:all).and_return(stories)
expect_any_instance_of(Story).to receive(:page).with(1).and_return(stories)
expect_any_instance_of(Story).to receive(:per).with(5).and_return(stories)
index.()
end
end
end
你的方法返回故事的枚举,而不是故事。当你让它回归一个故事时,它是错的。您可能想检查此方法的顺序,并且可以with this执行此操作,但他们不会检查接收参数。
如果您不关心params,或者您应该添加额外的检查,您可以这样做:
describe '#index' do
let(:stories) { [double(Story)] }
context 'when user is not logged in' do
it 'should get 5 last stories and assign to @stories' do
expect_any_instance_of(Story).to receive(:all).and_return(stories)
expect(stories).to receive(:page).and_return(stories)
expect(stories).to receive(:per).and_return(stories)
# or probably just this
expect_any_instance_of(Story).to receive_message_chain(:all, :page, :per) { stories }
get :index
end
end
end