简体   繁体   English

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

[英]Rails: Factories and Associations in Functional Tests

I'm trying to figure out why this doesn't work. 我试图弄清楚为什么这行不通。

Let's say you three models, User, Foo and Bar. 假设您使用三种模型:User,Foo和Bar。 In order for a bar to be created the user must first create and validate a foo object. 为了创建栏,用户必须首先创建并验证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

I'm trying to get a functional test working where if the user tries to make a new Bar without having a valid foo, they get redirected to the "new" action for a Foo. 我正在尝试进行功能测试,如果用户尝试在没有有效foo的情况下创建新Bar,他们将被重定向到Foo的“ new”操作。

I haven't had any problem with the redirect scenario. 重定向方案没有任何问题。 However, when I try to setup a user with a valid Foo object and try to get the "new" action for a Bar, it still gets redirected to the "new" action of the Foo controller. 但是,当我尝试为用户设置有效的Foo对象并尝试获取Bar的“新”操作时,它仍然会重定向到Foo控制器的“ new”操作。 It still doesn't acknowledge that the User has a Foo. 它仍然不承认用户有Foo。

Here's my controller: 这是我的控制器:

 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

This is the redirect function I have in my application controller which is called in my bar controller: 这是我在应用程序控制器中拥有的重定向功能,在我的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

Here's the Foo Factory: 这是Foo工厂:

Factory.define :foo do |f|
   #attributes
   f.valid true
   f.association :user
end

Instead I get redirected to " https://test.host:80/foos/new " The controller doesn't acknowledge that the user has a Foo... 取而代之的是,我被重定向到“ https://test.host:80/foos/new ”控制器不承认用户有Foo ...

The session is valid so this seems like a factory problem, but I'm not sure what it is. 该会话有效,因此这似乎是工厂问题,但我不确定这是什么。

I'm assuming that this is factory_girl. 我假设这是factory_girl。 You are calling Factory.build which doesn't save anything to the database, so you never have the foreign key value needed for your association. 您正在调用不会将任何内容保存到数据库的Factory.build ,因此您永远不会拥有关联所需的外键值。 Switch those to Factory.create and you should see a difference. 将它们切换到Factory.create ,您应该会看到区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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