测试 有关 RSpec 的一些问题

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

暂时就这么多问题

共收到 3 条回复

为毛大家都不屑于回答

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

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

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

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