登录用户而无需在rspec

时间:2015-09-30 03:50:27

标签: ruby-on-rails ruby-on-rails-4 rspec devise

使用RSPEC和DEVISE,我可以登录user来运行我的测试。但是,我最近遇到了我的方法的问题,因为使用before :each导致多个用户被创建,这导致我的测试中断。

我应该改变我的测试方法吗?或者更改我在用户中签名的方法?

campaign_controller_spec.rb

before :each do
  @user = FactoryGirl.create(:user)
  sign_in :user, @user
  @business = FactoryGirl.create(:business, user: @user)
end

describe "GET #index" do
  before :each do
    FactoryGirl.create(:active_campaign, business: @business)
    FactoryGirl.create(:inactive_campaign, business: @business)
  end

  it "no status or type filter" do
    get :index                                   #  <- LINE 22 OF ERROR
    expect(assigns(:campaigns).size).to eq 2
  end

  it 'status filter' do
    get :index, status: 'active'
    expect(assigns(:campaigns).size).to eq 1
  end
end

campaigns_controller.rb

def index
  # Get current user's campaigns
  @campaigns = current_user.business.campaigns

  # Filter by status (constraints are in routes)
  @campaigns = @campaigns.send(params[:status]) unless params[:status] == 'all'   #  <- LINE 7 OF ERROR
end

问题是所有广告系列属于规范中属于USER-1的business,但在控制器中,广告系列属于另一个用户(因为正在创建多个用户)有任何相关的广告系列。

确切的错误是:

  1) CampaignsController [Signed in] GET #index no status or type filter
     Failure/Error: get :index
     TypeError:
       nil is not a symbol nor a string
     # ./app/controllers/campaigns_controller.rb:7:in `index'
     # ./spec/controllers/campaigns_controller_spec.rb:22:in `block (4 levels) in <top (required)>'

小更新

我安装了Database Cleaner gem,它应该在测试之间清除DB。这是配置(以防它不正确):

#DatabaseCleaner
config.before(:suite) do
  DatabaseCleaner.strategy = :transaction
  DatabaseCleaner.clean_with(:truncation)
end

config.before(:each) do
  DatabaseCleaner.start
end

config.after(:each) do
  DatabaseCleaner.clean
end

1 个答案:

答案 0 :(得分:1)

使用factory_girl时,您需要使用database_cleaner gem之类的东西在测试之间清理数据库。退房:

https://github.com/DatabaseCleaner/database_cleaner#user-content-rspec-example

编辑:

意识到您的错误不是由您认为的错误引起的。这是因为当.send(params[:status])为零时你正在进行params[:status],因为它在调用get :index时没有传入...所以一旦.send(nil)被调用你得到了堆栈跟踪。