使用Mongoid,Rspec的未定义方法`reflect_on_association`

时间:2011-10-11 23:15:11

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

我正在学习一些Rails!但是现在,我似乎无法通过RSpec抛出的错误。错误如下:

  1) EntryMethodsController POST create with valid params creates a new EntryMethod
     Failure/Error: post :create,
     NoMethodError:
       undefined method `reflect_on_association' for "4e94ca4f66472f02ff00000a":String
     # ./app/controllers/entry_methods_controller.rb:43:in `create'
     # ./spec/controllers/entry_methods_controller_spec.rb:48:in `block (4 levels) in '

Finished in 0.29409 seconds
13 examples, 1 failure

Failed examples:

rspec ./spec/controllers/entry_methods_controller_spec.rb:47 # EntryMethodsController POST create with valid params creates a new EntryMethod
Done.

测试

  describe "POST create" do
    describe "with valid params" do
      before :each do
        @contest = FactoryGirl.create(:contest)
      end

      after :each do
        @contest.destroy
      end

      it "creates a new EntryMethod" do
        expect {
          post :create,
               :contest => @contest,
               :entry_method => FactoryGirl.attributes_for(:url_entry_method, :contest => @contest)
        }.to change(@contest.entry_methods, :count).by(1)
      end
   end
 end

控制器

def create
  @entry_method = Contest.find(params[:contest_id])
                  .entry_methods.new(params[:entry_method])

  respond_to do |format|
    if @entry_method.save
      format.html { redirect_to @entry_method, notice: 'Entry method was successfully created.' }
      format.json { render json: @entry_method, status: :created, location: @entry_method }
    else
      format.html { render action: "new" }
      format.json { render json: @entry_method.errors, status: :unprocessable_entity }
    end
  end
end

模型

class Contest
  include Mongoid::Document
  include Mongoid::Timestamps
  field :name, :type => String
  field :rules, :type => String
  field :start_date, :type => Time
  field :end_date, :type => Time

  embeds_many :entry_methods
end

class EntryMethod
  include Mongoid::Document
  field :url, :type => String
  field :string, :type => String

  embedded_in :contest
end

谢谢,非常棒的人。 :)

1 个答案:

答案 0 :(得分:2)

我认为这是因为你正在通过一个完整的@contest对象传递create动作的参数,而它实际上会期待Hash个属性。< / p>

您可以通过将对该操作的调用更改为此来解决此问题:

post :create,
     :contest => @contest.attributes,
     ...

我也让FactoryGirl为你创建对象,因为这可能导致唯一性验证或任何可能失败的事情。您应该使用FactoryGirl.build,而不是FactoryGirl.create