模型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
不知道如何修复并通过测试?
答案 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