rails 4 rspec用于工作,现在它失败了user.profile是nil

时间:2017-04-19 01:25:23

标签: ruby-on-rails rspec cancancan

这个测试曾经工作,但我无法弄清楚为什么停止。现在当我运行它时,other_user.profile等于nil。

测试:

require 'rails_helper'

describe "User" do
 describe "abilities" do
  subject(:ability){ Ability.new(user) }
  let(:other_user) { nil }

  context "not logged in (Guest)" do
    let(:other_user){ build(:user_with_profile) }

    it{ should be_able_to(:show, other_user.profile) }
  end
 end
end

工厂:

# users.rb factory
FactoryGirl.define do
  factory :user do
    email { Faker::Internet.email }
    password "secret"
  end

  factory :user_with_profile, parent: :user do
    after(:build) do |user|
    build(:profile, user: user)
  end
end

# profiles.rb factory
include ActionDispatch::TestProcess

FactoryGirl.define do
  factory :profile do |f|
    association :user, factory: :user
    f.about { Faker::Lorem.paragraph(2) }
    f.avatar { fixture_file_upload(Rails.root.join('spec', 'support', 'test.png'), 'image/png') }
  end  
end

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

尝试更改

factory :user_with_profile, parent: :user do
  after(:build) do |user|
    build(:profile, user: user)
  end
end

factory :user_with_profile, parent: :user do
  after(:build) do |user|
    user.profile = build(:profile)
  end
end