干涸Rspec测试

时间:2015-12-22 22:31:52

标签: ruby-on-rails ruby ruby-on-rails-4 factory-bot rspec3

我正在开发我的应用程序的管理仪表板部分,以及用户需要登录的每个操作。

所以例如这个测试:

describe 'GET #index' do
    let(:user) { create(:user) }

    before do
      sign_in user
    end

    it 'responds successfully with an HTTP 200 status code' do
      get :index
      expect(response).to be_success
      expect(response).to have_http_status(200)
    end

    it 'renders the index template' do
      get :index
      expect(response).to render_template('index')
    end

    it 'loads all of the tags into @tags' do
      tag1 = create(:tag)
      tag2 = create(:tag)
      get :index

      expect(assigns(:tags)).to match_array([tag1, tag2])
    end
  end

工作得很好,但我在考虑是否可以将用户创建和sign_in部分提取到可以用于所有这些管理测试的内容。我试过这个:

describe 'GET #index', admin: true do
 ....all the same as above, except user creation and before sign in block
end

然后在我的spec/spec_helper.rb中添加了以下内容:

config.before(:each, admin: true) do |_example|
  before do
    sign_in FactoryGirl.create(:user)
  end
end

不幸的是,这不起作用,有没有更好的方法可以做到这一点?完成同样的事情,我可以将登录代码放在一个地方,而不必在我的管理测试中重新过去。

我正在使用Rails 4和Rspec 3。

2 个答案:

答案 0 :(得分:1)

你有一个额外的块。删除它所以...

config.before(:each, admin: true) do |_example|
  before do
    sign_in FactoryGirl.create(:user)
  end
end

变成这个......

config.before(:each, admin: true) do
  sign_in FactoryGirl.create(:user)
end

另外,如果这些是控制器规格(就像它们看起来那样)那么......

describe 'GET #index' do

实际上应该是这样......

describe SomeController, type: :controller, admin: true do

答案 1 :(得分:0)

共享示例是清理规范和删除代码重复的好方法,请查看https://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-examples

相关问题