2

我的控制器如下所示:

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 

为这样的控制器编写什么是好的示例测试?

4

2 回答 2

1

您应该expect(story).to receive(:page).with(1)在调用之前设置get :index

get :indexbefore一个块移动到另一个it块:

it 'should get page 1' do                                                                                                
  expect(story).to receive(:page).with(1)
  get :index
end

PS,看起来你错过=了控制器动作

params[:page] ||= 1
于 2014-06-20T08:56:37.430 回答
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

您的方法返回故事的枚举,而不是一些故事。当你让它返回一个故事时,它是错误的。您可能想检查此方法的顺序,您可以使用此方法执行此操作,但它们不检查接收参数。

如果你不关心参数或者你应该添加额外的检查,你可以这样做:

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
于 2014-06-20T08:58:15.877 回答