[英]How do I test association in rails controller with rspec?
I have an article model which has many comments and the comment belongs to one article. 我有一个包含很多评论的文章模型,该评论属于一篇文章。 this is my create method for comments_controller.rb: 这是我的comment_controller.rb的创建方法:
def create
@comment = Comment.new(comment_params)
@comment.article_id = params[:article_id]
@comment.save
redirect_to article_path(@comment.article)
end
I want to know what's the best approach to test this action with rspec. 我想知道用rspec测试此操作的最佳方法是什么。 and I want to know testing methods for association in controller at all. 我想知道控制器中关联的测试方法。
thank you experts. 谢谢专家。
You can access your comment object within your tests using assigns
method: 您可以使用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
The above is just a guideline, you will need to modify it depending on your exact requirements. 以上仅是一个准则,您将需要根据实际要求对其进行修改。
I suggest this codes. 我建议使用此代码。 This code is using FactoryGirl. 这段代码正在使用FactoryGirl。
factory_girl is a fixtures replacement with a straightforward definition syntax... https://github.com/thoughtbot/factory_girl Please add gem 'factory_girl_rails'
to Gemfile
. factory_girl是用简单的定义语法替换的灯具... https://github.com/thoughtbot/factory_girl请将Gemfile
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
uhh, I am not English native speaker. 呃,我不是英语为母语的人。 so If it
's sentence is not natural, please modify sentences. 所以如果it
的句子是不自然的,请修改句子。 :-( :-(
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.