测试 有关 RSpec 的一些问题

sanvi · 2013年09月04日 · 最后由 sanivbyfish 回复于 2013年09月04日 · 3245 次阅读
#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?

暂时就这么多问题

为毛大家都不屑于回答

代码太长了,没细看。 只说问题 2 的两种解决方法,任选其一:

  1. create改成 FactoryGirl.create
  2. 在 spec_helper.rb 里面添加 config.include FactoryGirl::Syntax::Methods 这样以后就不用每次都写 FactoryGirl.xxx

#2 楼 @zhaowenchina 非常感谢 那么请问一下,我怎么构建一个带 attachment 的 build 去调用 create 这个 action 呢?

需要 登录 后方可回复, 如果你还没有账号请 注册新账号