使用RSPEC和FactoryGirl进行控制器测试失败,出现错误:1得到:0

时间:2016-12-09 13:43:36

标签: ruby-on-rails rspec factory-bot rspec-rails

模型Organization有许多Events,而Event始终属于Organization

我的Events controller测试,文件controllers/events_controller_spec.rb是:

require 'rails_helper'

RSpec.describe EventsController, type: :controller do

  describe "POST #create" do
    context "with valid attributes" do
      it "create new event" do
        post :create, event: attributes_for(:event)
        expect(Event.count).to eq(1)
      end
    end

  end
end

这是我的factories/organizations.rb文件:

FactoryGirl.define do
  factory :organization do
    organization_name { Faker::Company.name }
  end

  factory :invalid_organization, class: Organization do
    organization_name ''
  end
end

这是我的factories/events.rb文件:

FactoryGirl.define do
  factory :event do
    event_description { Faker::Lorem.sentence(3) }
    host_name { Faker::Internet.domain_name }
    organization { create(:organization) }
  end
end

基于以上所述,我假设在创建任何organization之前创建event

我的测试因此错误而失败。

$ rspec spec/controllers/events_controller_spec.rb

Failures:

  1) EventsController POST #create with valid attributes create new event
     Failure/Error: expect(Event.count).to eq(1)

       expected: 1
            got: 0

       (compared using ==)
     # ./spec/controllers/events_controller_spec.rb:9:in `block (4 levels) in <top (required)>'

Finished in 1.53 seconds (files took 9.03 seconds to load)
1 example, 1 failure

不知道如何修复并通过测试?

3 个答案:

答案 0 :(得分:0)

尝试将其移到期望

it "create new event" do
  expect do
    post :create, { event: attributes_for(:event) }
  end.to change(Event, :count).by(1)
end

答案 1 :(得分:0)

试试这个

it "create new event" do
  event_attributes = FactoryGirl.build(:event).attributes.symbolize_keys 
  post :create, event: event_attributes
  expect(Event.count).to eq(1)
end

希望有所帮助!

答案 2 :(得分:0)

问题是attributes_for(:event)包含属性organization,它是Organization个对象。这不是控制器方法期望从new表单和event_params接收的内容,并且未创建事件。

更改它以使伪装属性只是id ...

FactoryGirl.define do
  factory :event do
    event_description { Faker::Lorem.sentence(3) }
    host_name { Faker::Internet.domain_name }
    organization_id { create(:organization).id }
  end
end