2015-10-16 71 views
1

我有User(我使用Devise)和Profile模型,其中User has_one Profile作爲它們的關係。運行rspec測試時出錯。以下是我的規範在用戶更新他/她的個人資料時處理的內容。更新時Rspec has_one關係錯誤

spec/controller/profiles_controller_spec.rb

RSpec.describe ProfilesController, type: :controller do 
    let(:profile) { FactoryGirl.create(:profile) } 
    let (:valid_attributes) { FactoryGirl.attributes_for(:profile) } 
    let (:invalid_attributes) { FactoryGirl.attributes_for(:profile).merge({fname: nil}) } 
    let(:user) { FactoryGirl.create(:user) } 
    let(:valid_session) { sign_in(user) } 

    describe "PUT #update" do 
    before { valid_session } 

    context "with valid attributes" do 
     it "saves valid profile" do 
     expect do 
      put :update, { id: profile.id, profile: { fname: "Cena" } } 
     end.to change{ profile.reload.fname }.to("Cena") 
     end 
    end 

spec/factories/profiles.rb

FactoryGirl.define do 
    factory :profile do 
    user 
    fname "John" 
    lname "Doe" 
    avatar "my_avatar" 
    end 
end 

app/controller/profiles_controller.rb

class ProfilesController < ApplicationController 

private 

    def user_params 
    params.require(:user).permit(:id, :login, :email, 
     profile_attributes: [ 
     :id, :user_id, :fname, :lname, :avatar, :avatar_cache 
     ]) 
    end 

end 

這裏是運行時錯誤rspec spec/controllers/accounts_controller_spec.rb

Failures: 

    1) AccountsController PUT #update with valid attributes saves valid profile 
    Failure/Error: put :update, {id: profile.id, user_id: user.id, profile: { fname: "Cena" }} 
    ActionController::ParameterMissing: 
     param is missing or the value is empty: user 

回答

1
let(:user) { FactoryGirl.create(:user) } 
    let(:profile) { FactoryGirl.create(:profile, user_id: user.id) } 

    describe "PUT #update" do 
    before { valid_session } 

    context "with valid attributes" do 
     it "saves valid profile" do 
     expect do 
      put :update, id: user.id, user: { profile_attributes: { user_id: user.id, fname: "Cena" } } 
     end.to change{ profile.reload.fname }.to("Cena") 
     end 
    end 
    end 
+0

仍然沒有工作..然後我得到了另一個錯誤時使用你的解決方案: 'NoMethodError:undefined method「permit」' – AmirolAhmad

+0

你可以嘗試我更新的答案,看看是否有用? –

+0

我得到這個錯誤''id「在示例(例如」it「塊)中或者來自在示例範圍中運行的構造(例如」之前「,」let「等)不可用。它僅適用於一個示例組(例如「描述」或「上下文」塊)。' – AmirolAhmad

0

您發佈的profiles_controller.rb代碼缺少更新操作(並且類名稱爲AccountController),但我想您正在執行類似user.update(user_params)的操作。

如果是這種情況,如錯誤所述,從控制器規格傳遞的參數沒有:user鍵,並且導致錯誤。

從#user_params方法和錯誤假設,傳遞給控制器​​規範後的PARAMS需要如下所示:

{ 
    user: { 
    id: xxx, ..., 
    profile_attributes: { 
     id: xxx, 
     fname: xxx, ... 
    } 
    } 
}