[英]Rails: Factories and Associations in Functional Tests
我試圖弄清楚為什么這行不通。
假設您使用三種模型:User,Foo和Bar。 為了創建欄,用戶必須首先創建並驗證foo對象。
Class User #snip!
has_many :foos
has_many :bars
Class Foo #snip!
belongs_to :user
has_many :bars
Class Bar #snip!
belongs_to :user
belongs_to :foo
我正在嘗試進行功能測試,如果用戶嘗試在沒有有效foo的情況下創建新Bar,他們將被重定向到Foo的“ new”操作。
重定向方案沒有任何問題。 但是,當我嘗試為用戶設置有效的Foo對象並嘗試獲取Bar的“新”操作時,它仍然會重定向到Foo控制器的“ new”操作。 它仍然不承認用戶有Foo。
這是我的控制器:
class BarsControllerTest < ActionController::TestCase
setup :activate_authlogic
def setup
@request.env['HTTPS'] = nil
@user = Factory.build(:user)
@foo = Factory.build(:foo, :user => @user)
end
test "should get new when user has a valid foo" do
@request.env['HTTPS'] = 'on'
UserSession.create(@user)
get :new
assert_response :success
end
這是我在應用程序控制器中擁有的重定向功能,在我的bar控制器中稱為:
def foo_required
if current_user && @current_user.foos.valid.empty? && @current_user.foos.empty?
flash[:notice] = "You must have a verified foo in order to create a Bar!"
redirect_to new_foo_path
elsif current_user && @current_user.foos.valid.empty?
flash[:notice] = "You must verify your foos in order to create a Bar!"
redirect_to foos_path
end
end
這是Foo工廠:
Factory.define :foo do |f|
#attributes
f.valid true
f.association :user
end
取而代之的是,我被重定向到“ https://test.host:80/foos/new ”控制器不承認用戶有Foo ...
該會話有效,因此這似乎是工廠問題,但我不確定這是什么。
我假設這是factory_girl。 您正在調用不會將任何內容保存到數據庫的Factory.build
,因此您永遠不會擁有關聯所需的外鍵值。 將它們切換到Factory.create
,您應該會看到區別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.