我已經構建了一個基於Hartl課程的應用程序 - 直到幷包括第9.2節(認證)。從那裏我試圖通過添加組織模型來擴展功能。最初,我嘗試使用腳手架生成命令行功能,決定它已經建立了太多,將其翻轉並手動構建。我相信我可能搞砸了我的遷移(見下文)。我使用Rails v4.1.1,Rspec 3.0.0和Capybara 2.2.0 - 所有數據庫都是postgres。Rspec在嘗試測試嵌套屬性時拋出的未知屬性錯誤
一個組織可以擁有多個用戶,而每個用戶只屬於一個組織。
我應該注意到,在我自己的機器上使用開發環境,我有組織在用戶註冊過程中正常工作的領域 - 它創建一個新用戶,我可以正確查看組織和用戶頁面,並且有應用程序的性能沒有出現任何錯誤。我的問題,當我使用Rspec的測試測試開始 - 拋出了一系列的錯誤是這樣的:
ActiveModel::MissingAttributeError:
can't write unknown attribute 'organization_id'
我的模型:
class Organization < ActiveRecord::Base
validates :organization_name, presence: true, length: { maximum: 50 }
has_many :users
end
class User < ActiveRecord::Base
belongs_to :organization
accepts_nested_attributes_for :organization
before_save { self.email = email.downcase }
before_create :create_remember_token, :create_organization
validates :name, presence: true, length: {maximum: 50}
VALID_EMAIL_REGEX = /\A[\w+\-.][email protected][a-z\d\-]+(?:\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, format: {with: VALID_EMAIL_REGEX}, uniqueness: {case_sensitive: false}
has_secure_password
validates :password, length: {minimum: 6}
def create_organization
self.organization = Organization.create(:organization_name => Organization.organization_name) unless self.organization.present?
end
我的工廠:
FactoryGirl.define do
factory :organization do
organization_name "Orgname"
end
factory :user do
association :organization
name "A Name"
email "[email protected]"
password "foobar"
password_confirmation "foobar"
end
end
一個例子Rspec的測試套件:
describe "edit" do
let(:organization) { FactoryGirl.create(:organization) }
let(:login) { FactoryGirl.create(:login,
:organization => organization,
:user => FactoryGirl.create(:user)) }
before do
sign_in login
visit edit_user_path (user)
end
我schema.rb文件:
ActiveRecord::Schema.define(version: 20140619041326) do
create_table "organizations", force: true do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.string "organization_name"
end
create_table "users", force: true do |t|
t.string "name"
t.string "email"
t.datetime "created_at"
t.datetime "updated_at"
t.string "password_digest"
t.integer "organization_id"
t.string "remember_token"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_index "users", ["organization_id"], name: "index_users_on_organization_id", using: :btree
add_index "users", ["remember_token"], name: "index_users_on_remember_token", using: :btree
end
這可能是值得一提的是在這裏當我第一次開始運行我使用哈特爾的書推薦Rspec的版本測試 - 這意味着我必須通過從開發DB的變化給力使用bin/rake dg:migrate RAILS_ENV = test命令行函數來測試數據庫。每次我跑了這一點,我schema.rb文件(如上面貼)就失去了行
t.integer "organization_id"
,我不得不耙分貝得到它的再次合作。
我意識到這裏有很多信息,而且我的問題可能很愚蠢(我對語言和框架很陌生,這是我的第一個應用程序),但它讓我生氣。過去一週,我花了很多時間試圖找出當實際的應用程序本身工作時爲什麼測試會被破壞。
任何幫助將不勝感激。
我已經找到了問題 - 顯然軌道4不會自動更新spec_helper使用'的ActiveRecord :: Migration.maintain_test_schema'的模式 - 而不是你仍然需要使用「rake db:test:prepare」。 不過雖然這已擺脫了我一些錯誤,我仍然得到3個主要錯誤: 1)它不喜歡我廠「登陸」(我是複製這似乎暗示這會工作其他代碼) 2.)在用戶頁面rspec測試它找不到字段「機構名稱」 3.)它說上述「create_organization」功能未定義方法「organization_name」 任何想法? – Zoinks10