开发者

Undefined method `reflect_on_association` using Mongoid, Rspec

开发者 https://www.devze.com 2023-04-12 03:47 出处:网络
I\'m learning me some Rails! But right now, I can\'t seem to get past an error RSpec is throwing. The error is as follows:

I'm learning me some Rails! But right now, I can't seem to get past an error RSpec is throwing. The error is as follows:

  1) EntryMethodsController POST create with valid params creates a new EntryMethod
     Failure/Error开发者_如何学Go: 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.

Test

  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

Controller

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

Models

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

Thanks, SO awesome people. :)


I reckon this is because you're passing through a full @contest object to the parameters of the create action, when it's actually going to be expecting a Hash of attributes.

You can fix this by changing your call to that action to this:

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

I would also not get FactoryGirl to create the object for you, as that may lead to uniqueness validations or whatever possibly failing. You should be using FactoryGirl.build, and not FactoryGirl.create.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号