#models/build.rb
class Build
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :attachment
end
#models/attachment.rb
class Attachment
include Mongoid::Document
include Mongoid::Timestamps
mount_uploader :file, AttachmentUploader
end
#spec/controllers/builds_controller_spec.rb
require 'spec_helper'
describe BuildsController do
before(:all) do
@build = FactoryGirl.build(:build)
end
it "has a valid factory" do
FactoryGirl.create(:app).should be_valid
end
describe "POST 'create'" do
let(:user) {login_user}
let(:attachment) { create(:attachment) }
let(:build) { create(:build, attachment: attachment) }
context 'when upload apk' do
it 'creates with apk' do
post 'create', :build => FactoryGirl.attributes_for(:build)
expect(response).to redirect_to build_path(build)
end
end
end
end
#factories/builds.rb
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :build do |f|
#fields
attachment
# { FactoryGirl.build(:attachment) }
note {Faker::Lorem.sentence(10)}
end
end
#factories/attachments.rb
# Read about factories at https://github.com/thoughtbot/factory_girl
include ActionDispatch::TestProcess
FactoryGirl.define do
factory :attachment do |f|
file { Rack::Test::UploadedFile.new(Rails.root.join(*%w[spec factories data attachment calc-android-china.apk]), 'application/vnd.android.package-archive') }
end
end
代码如上,有一些问题
首先
context 'when upload apk' do
it 'creates with apk' do
post 'create', :build => FactoryGirl.attributes_for(:build)
expect(response).to redirect_to build_path(build)
end
end
其中 1.FactoryGirl.attributes_for(:build) 是不是会直接拿 FactoryGirl 里面构建的 build,那么我后面直接用 build 是否跟这个是同一个对象? 2.rspec 出现以下错误
1) BuildsController POST 'create' when upload apk creates with apk
Failure/Error: let(:attachment) { create(:attachment) }
NoMethodError:
undefined method `create' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1::Nested_1:0x007fb5d3ddddb8>
为什么呢?不是可以直接构建吗? 3.我 build 里面是关联 attachment,那么 let(:build) { create(:build, attachment: attachment) },我在后面应该能拿到 build.attachment,那为何是 nil?
暂时就这么多问题