繁体   English   中英

Rails:功能测试中的工厂和协会

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM