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. In order for a bar to be created the user must first create and validate a foo object.
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.
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. It still doesn't acknowledge that the User has a 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:
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:
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...
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. 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. Switch those to Factory.create
and you should see a difference.
精彩评论