分配 returns 零 rspec rails

assigns returns nil rspec rails

我正在尝试测试客户控制器中的 put 方法。问题是 assigns(:customer) 总是 returns nil,所以第一个测试失败了。然而,第二个测试完美运行,所以我不明白为什么第一个测试失败,因为正确的客户是从更新方法中的参数中检索到的。

  describe "PUT #update" do
    before :each do
      @customer = create(:customer, user: @user)
    end

    context "with valid attributes" do
    it "locates the requested customer" do
      put :update, id: @customer.id, customer: FactoryGirl.attributes_for(:customer).merge({user_id: @user.id})
      assigns(:customer).should eq @customer
    end

    it "should save customer to the database" do
      put :update, id: @customer, customer: {name: 'lorem', mail: 'lorem@gmail.com', address: 'lorem_address', phone:@customer.phone, user_id: @customer.user.id}
      @customer.reload
      expect(@customer.name).to eq 'lorem'
      expect(@customer.mail).to eq 'lorem@gmail.com'
      expect(@customer.address).to eq 'lorem_address'
    end
  end


FactoryGirl.define do
  factory :user do
    email {Faker::Internet.email}
    password {Faker::Internet.password(10)}
  end
end


FactoryGirl.define do
  factory :customer do
    association :user
    name Faker::Name.name
    sequence(:mail) {|i| "example#{i}@example.com"}
    address Faker::Address.street_address
    phone Faker::PhoneNumber.phone_number
  end
end


def update
    debugger
    customer = Customer.find(params[:id])
    if customer.update_attributes(customers_params)
      flash[:success] = 'Customer information updated successfully'
      redirect_to customers_path
    else
      @customer = customer
      render :edit
    end
  end

谢谢

由此post

assigns is a hash, accessible within Rails tests, containing all the instance variables that would be available to a view at this point...

关键字是instance variables,即以@开头的变量。

将您的 update 操作修改为以下内容应该会使您的测试通过

def update
    debugger
    @customer = Customer.find(params[:id])
    if @customer.update_attributes(customers_params)
      flash[:success] = 'Customer information updated successfully'
      redirect_to customers_path
    else
      render :edit
    end
end