ruby on rails - How to call the create action from the controller in RSpec -


i have controller create action creates new blog post, , runs additional method if post saves successfully.

i have separate factory girl file params post want make. factorygirl.create calls ruby create method, not create action in controller.

how can call create action controller in rspec? , how send params in factory girl factories.rb file?

posts_controller.rb

def create   @post = post.new(params[:post])   if @post.save     @post.my_special_method     redirect_to root_path   else     redirect_to new_path   end end 

spec/requests/post_pages_spec.rb

it "should run special method"   @post = factorygirl.create(:post)   @post.user.different_models.count.should == 1 end 

post.rb

def my_special_method   user = self.user   special_post = post.where("group_id in (?) , user_id in (?)", 1, user.id)   if special_post.count == 10     differentmodel.create(user_id: user.id, foo_id: foobar.id)   end end    

end

request specs integration tests, using capybara visit pages user might , perform actions. wouldn't test create action request spec @ all. you'd visit new item path, fill in form, hit submit button, , confirm object created. take @ railscast on request specs great example.

if want test create action, use controller spec. incorporating factorygirl, this:

it "creates post"   post_attributes = factorygirl.attributes_for(:post)   post :create, post: post_attributes   response.should redirect_to(root_path)   post.last.some_attribute.should == post_attributes[:some_attribute]   # more lines above, or remove `:id`   #   `post.last.attributes` , compare hashes. end  "displays new on create failure"   post :create, post: { some_attribute: "some value doesn't save" }   response.should redirect_to(new_post_path)   flash[:error].should include("some error message") end 

these tests need related creation. in specific example, i'd add third test (again, controller test) ensure appropriate differentmodel record created.


Comments

Popular posts from this blog

php - cannot display multiple markers in google maps v3 from traceroute result -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -