NoMethodError:未定义的方法`user =' rspec的

时间:2018-05-18 09:56:52

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

我将此工厂文件用于user型号:

FactoryBot.define do
  factory :user do |f|
    f.sequence(:first_name) { |n| "#{Faker::Name.first_name}foo#{n}" }
    f.sequence(:last_name) { |n| "#{Faker::Name.last_name}foo#{n}" }
    f.sequence(:email) { |n| "foo#{n}@example.com" }
    f.password "foobar"
    f.password_confirmation { |u| u.password }
    f.sequence(:confirmed_at) { Date.today }
    f.sequence(:telephone_number) { Faker::Number.number(10) }
    f.sequence(:mobile_phone_number) { Faker::Number.number(10) }
    f.sequence(:verification_code) { '0000' }
    f.sequence(:is_verified) { false }
  end
end

Order.rb工厂是:

FactoryBot.define do
  factory :order do
    association :store
    association :user
    total_price Faker::Number.positive
    total_discount Faker::Number.positive
  end
end

order模型应该有这三个FK,其中两个来自User

class Order < ApplicationRecord
  belongs_to :customer, class_name: 'User'
  belongs_to :carrier, class_name: 'User'
  belongs_to :store
end

并在order_controllers_spec.rb文件中,我得到了这些:

let(:customer) { FactoryBot.create(:user) }
let(:carrier) { FactoryBot.create(:user) }
let(:store) { FactoryBot.create(:store) }
let(:order) { FactoryBot.create(:order, customer_id: customer.id, carrier_id: carrier.id, store_id: store.id) }

每次我运行show测试时,

describe "GET show" do
    it 'has a 200 status code' do
        get :show, params: { id: order_item.id }
        expect(response.status).to eq(200)
    end
end

我收到了这个错误

Failure/Error: let(:order) { FactoryBot.create(:order, customer_id: customer.id, carrier_id: carrier.id, store_id: store.id) }

 NoMethodError:
   undefined method `user=' for #<Order:0x00007fcd2efc5118>

关于如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:4)

我认为在Order的工厂定义中,您使用的是user,而不是customercarrier作为您的Order模型定义。< / p>

association :customer, factory: :user
association :carrier,  factory: :user