如何使用rspec测试rails控制器中的关联?

时间:2016-02-03 09:56:05

标签: ruby-on-rails associations rspec-rails

我有一篇文章模型有很多评论,评论属于一篇文章。这是我对comments_controller.rb的创建方法:

def create
  @comment = Comment.new(comment_params)
  @comment.article_id = params[:article_id]

  @comment.save
  redirect_to article_path(@comment.article)
end

我想知道使用rspec测试此操作的最佳方法是什么。我想知道控制器中关联的测试方法。

谢谢专家。

2 个答案:

答案 0 :(得分:1)

您可以使用assigns方法访问测试中的评论对象:

describe CommentsController, type: :controller
  let(:comment_params) {{ <correct params goes here>}}
  let(:article_id) { (1..100).sample }
  let(:create!) { post :create, comment: comment_params, article_id: article_id }

  it "creates new comment" do
    expect { create! }.to change { Comment.count }.by 1
  end

  it "assigns given comment to correct article"
    create!
    expect(assigns(:comment).article_id).to eq params[:article_id]
  end
end

以上只是一个指南,您需要根据您的具体要求进行修改。

答案 1 :(得分:1)

我建议使用此代码。 此代码使用FactoryGirl。

factory_girl是一个灯具替代品,具有直观的定义语法... https://github.com/thoughtbot/factory_girl 请将gem 'factory_girl_rails'添加到Gemfile

 def create
   @comment = Comment.new(comment_params)
   @comment.article_id = params[:article_id]

   if @comment.save
     redirect_to article_path(@comment.article)
   else
     redirect_to root_path, notice: "Comment successfully created" # or you want to redirect path
   end
 end

 describe "POST #create" do
   let(:article_id) { (1..100).sample }

   context 'when creation in' do
     it 'creates a new comment' do
       expect { post :create, comment: attributes_for(:comment), article_id: article_id }.to change {
        Comment.count
       }.from(0).to(1)
     end

     it 'returns same article_id' do
       post :create,  comment: attributes_for(:comment), article_id
       expect(assigns(:comment).article_id).to eq(article_id)
     end
   end

   context 'when successed in' do
     before { post :create, comment: attributes_for(:comment), article_id }

     it 'redirects article path' do
       expect(response).to redirect_to(Comment.last.article)
     end
   end

    context 'when unsuccessed in' do
     before { post :create, comment: attributes_for(:comment), article_id }

     it 'does not redirect article path' do
       expect(response).to redirect_to(root_path)
     end
   end
 end
呃,我不是英语母语人士。所以,如果it的句子不自然,请修改句子。 : - (